当前位置:网站首页>Seven principles of software design
Seven principles of software design
2022-06-24 22:21:00 【Nice2cu_ Code】
Software design principles
List of articles
One 、 Opening and closing principle
Open to expansion , Turn off for changes . When the program needs to be extended , You can't change the old code , I want to do that , Interfaces and abstract classes are required .
Changeable details in software can be extended from abstract derived implementation classes , When the software needs to change , You just need to re derive an implementation class according to the requirements .
give an example :
【 example 】 Skin design of Sogou input method
analysis : Skin is Sogou input method (SouGouInput) Properties of , Users can change the skin of the input method according to their preference . These skins have something in common , For example, all by pictures 、 Input window, etc . You can define an abstract class skin for it (AbstractSkin), And every specific skin (DefaultSpecificSkin and HeimaSpecificSkin) Is its subclass . As shown in the figure below :

If you have new skin , Just define a new implementation class , There is no need to modify the abstract skin class .
Two 、 Richter substitution principle
Richter substitution principle : Any place where a base class can appear , Subclasses must appear . Easy to understand : When a subclass inherits a parent class , In addition to adding new methods to complete the new functions , Try not to override the methods of the parent class .
If you can accomplish new functions by overriding the methods of the parent class , It will reduce the reusability of the whole inheritance system
give an example :
【 example 】 A square belongs to a rectangle
In the field of Mathematics , A square is undoubtedly a rectangle , It is a rectangle of equal length and width . therefore , A software system related to geometry is developed , So it's natural for a square to inherit from a rectangle , As shown in the figure below :
RectangleDemo Class is a component in a software system , It has one resize Methods depend on base classes Rectangle,resize The method is RectandleDemo A method in class , Used to achieve the effect that the width gradually increases until it is greater than the length .

The code is as follows :
Square (Square):
Because the length and width of a square are the same , So in method setLength and setWidth in , You need to assign the same value to both length and width :
public class Square extends Rectangle {
@Override
public void setLength(double length) {
super.setLength(length);
super.setWidth(length);
}
@Override
public void setWidth(double width) {
super.setLength(width);
super.setWidth(width);
}
}
RectangleDemo class :
resize() The method is as follows :
public static void resize(Rectangle rectangle) {
while (rectangle.getWidth() <= rectangle.getLength()) {
rectangle.setWidth(rectangle.getWidth() + 1);
}
}
Run this code and you'll find , If you pass a rectangle as a parameter resize Method , You'll see the effect of increasing the width of the rectangle , When the width is greater than the length , The code will stop , The result of this behavior is expected .
If you pass a square as an argument resize After the method , You'll see that the width and the length of the square are growing ( Square rewritten setWidth Method will make the length and width consistent ), The code will run all the time , Until the system generates an overflow error . therefore , The normal rectangle is suitable for this code , Square is not suitable for .
Improvement :
Create an interface Quadrilateral , Define the general abstract method to obtain the length and width of quadrilateral , Rectangle and square implement this interface respectively , Define specific methods for setting length and width , Here's the picture :

here ,resize Method can only calculate rectangles , Cannot calculate square , Solved previous problems .
3、 ... and 、 Dependence Inversion Principle
High level modules should not rely on low level modules , Both should rely on their abstractions ; Abstraction should not depend on details , Details should depend on abstraction .
rely on :A Class dependence B class , That is to say A Class B A member variable of type .
give an example :
【 example 】 Assemble the computer
Now I'm going to assemble a computer , Need accessories cpu, Hard disk , Memory module . Only these configurations are available , The computer can run normally . choice cpu There are many options , Such as Intel,AMD etc. , Seagate can be selected as the hard disk , Western mathematics, etc , Memory module can choose Kingston , Pirate ship, etc , The class diagram is as follows :
Computer Class directly depends on the specific hardware :

The biggest drawback of this approach is , Computer cpu Can only be Intel Of , The memory module can only be Kingston's , The hard disk can only be Seagate's .
Improve according to the principle of dependence reversal :
Give Way Computer Class dependency abstraction ( The interface of various accessories ), Instead of depending on the specific implementation class of each component , The class diagram is as follows :

If there are products of different brands in the later stage , You only need to implement the corresponding interface , There is no need to modify Computer class .
Four 、 Interface isolation principle
- A class should not be forced to rely on methods it does not use :

- The dependency of one class on another should be based on the smallest interface :

give an example :
【 example 】 Security door cases
There is one HeiMa Brand safety door , The safety door has the function of fire prevention 、 waterproof 、 Anti theft function . It can be used to prevent fire , waterproof , The anti-theft function is extracted into an interface , Form a set of norms . The class diagram is as follows :

Now if you need to create a safety door of other brands , The safety door only has anti-theft function 、 Waterproof function , Obviously, if you do SafetyDoor The interface violates the principle of interface isolation , Need to improve , Extract different functions into different interfaces , The class diagram is as follows :

such , Different safety doors , What functions are needed to implement the corresponding interfaces .
5、 ... and 、 Dimitar's law
Dimiter's law is also called Minimum knowledge principle .
If there is no need for direct communication between two software entities , Then there should be no direct mutual calls , The call can be forwarded through a third party . The goal is to reduce the coupling between classes , Improve the relative independence of modules :

It can be understood as , Just talk to friends , Don't talk to strangers .
In Dimitar's law “ friend ” Refer to : The current object itself 、 Member object of current object 、 The object created by the current object 、 Method parameters of current object, etc , These objects are associated with the current object 、 Aggregate or combine relationships , Methods that can directly access these objects .
give an example :
【 example 】 Examples of the relationship between stars and agents
Many daily affairs of stars are handled by agents , Such as meeting with fans , Business negotiation with media companies, etc . The agent here is a friend of the star , Fans and media companies are strangers to stars , So it's good to use Dimitar's law , The class diagram is as follows :

6、 ... and 、 Synthetic multiplexing principle
Try to use association relations such as composition or aggregation to achieve , Second, consider using inheritance relationship to achieve .
Disadvantages of inheritance :
- Inheritance destroys the encapsulation of classes . Because inheritance exposes the implementation details of the parent class to the child class , The parent class is transparent to the child class .
- The coupling degree between subclass and parent is high . Any change in the parent class will lead to a change in the implementation of the child class , This is not conducive to class expansion and maintenance .
Advantages of combination or aggregation :
- Low coupling between objects . You can declare... At the member position of a class .
give an example :
【 example 】 Car classification management procedure
Press the car “ Power source ” It can be divided into gasoline vehicles 、 Electric cars, etc ; Press “ Color ” It can be divided into white cars 、 Red cars, etc . If you consider both categories , There are many combinations . The class diagram is as follows ( Inheritance reuse ):

From the above class diagram, we can see that many subclasses are generated by inheritance reuse , If there is a new power source or a new color now , You need to define a new class . You can try to change inheritance reuse to Aggregate reuse , Here's the picture :

Comparison of the two , Suppose you want to add a new type of light energy car :
For inheritance reuse ( Added three classes )

For aggregation reuse ( Only one class has been added )

7、 ... and 、 Principle of single responsibility
Do not have more than one reason for class changes .
such as ,Class Class has two responsibilities a and b,a Changes will result in changes to the class , In turn, it may lead to confusion about responsibilities b The impact of function ; Empathy ,b Changes will result in changes to the class , In turn, it may lead to confusion about responsibilities a The impact of function . That is to say, responsibility a and b Can change the class , Not meeting the principle of single responsibility .
Solution : A class or interface is responsible for only one responsibility .
benefits : Reduce class complexity , Improve the readability of the class 、 Maintainability , Reduce the risk of change .
give an example :
Use a class to describe the scene of animals breathing :
class Animal{
public void breathe(String animal){
System.out.println(animal+" Breathe the air ");
}
}
public class Client{
public static void main(String[] args){
Animal animal = new Animal();
animal.breathe(" cattle ");
}
}
Running results : Cows breathe air .
A problem arises , Not all animals breathe air , For example, fish breathe water . If we follow the principle of single responsibility when revising , Need to put Animal Class is subdivided into terrestrial animals Terrestrial , aquatic Aquatic , The code is as follows :
class Terrestrial{
public void breathe(String animal){
System.out.println(animal+" Breathe the air ");
}
}
class Aquatic{
public void breathe(String animal){
System.out.println(animal+" Breathing water ");
}
}
public class Client{
public static void main(String[] args){
Terrestrial terrestrial = new Terrestrial();
terrestrial.breathe(" cattle ");
Aquatic aquatic = new Aquatic();
aquatic.breathe(" fish ");
}
}
Running results : Cows breathe air , Fish breathe water .
If you modify it like this, it will cost a lot , In addition to decomposing the original class , Also need to modify the client . And modify the class directly Animal It's against the principle of single responsibility to achieve the goal , But the cost is much smaller , The code is as follows :
class Animal{
public void breathe(String animal){
if(" fish ".equals(animal)){
System.out.println(animal+" Breathing water ");
}else{
System.out.println(animal+" Breathe the air ");
}
}
}
But there is one drawback to this approach , The more animal types ,if More judgment .
therefore , Whether to use the principle of single responsibility , It needs to be decided according to the specific situation , For example , The logic is simple , Can violate the principle of single responsibility .
边栏推荐
- leetcode_ one thousand three hundred and sixty-five
- Ansible basic configuration
- 04A interrupt configuration
- Flutter: Unsupported value: false/true
- Notes on writing questions (18) -- binary tree: common ancestor problem
- SAP interface debug setting external breakpoints
- socket(2)
- Development of live broadcast software app, and automatic left-right sliding rotation chart advertising
- leetcode-201_ 2021_ 10_ seventeen
- Reduce the pip to the specified version (upgrade the PIP through CMP and reduce it to the original version)
猜你喜欢

字符串习题总结2

好想送对象一束花呀

Want to be a test leader, do you know these 6 skills?

Redis+caffeine two-level cache enables smooth access speed

The logic of "Ali health" has long changed

KT6368A蓝牙芯片的主从机之前透传功能说明,2.4G跳频自动连接

Docker 安装 MySQL 8.0,详细步骤

降低pip到指定版本(通過PyCharm昇級pip,在降低到原來版本)

C language - keyword 1

故障安全移动面板KTP900F Mobile下载程序提示无法下载,目标设备正在运行或未处于传输模式的解决办法
随机推荐
The process from troubleshooting to problem solving: the browser suddenly failed to access the web page, error code: 0x80004005, and the final positioning: "when the computer turns on the hotspot, the
虚拟人的产业发展现状
Huada 04A operating mode / low power consumption mode
Main steps of system test
TKKC round#3
Two implementation methods of stack
权限想要细化到按钮,怎么做?
Ansible basic configuration
专科出身,2年进苏宁,5年跳阿里,论我是怎么快速晋升的?
直播软件app开发,左右自动滑动的轮播图广告
解决dataframe报错ValueError: Cannot take a larger sample than population when ‘replace=False‘
DP problem set
Find the maximum value in each tree row [extension of one of the hierarchical traversals]
60 divine vs Code plug-ins!!
LINQ query collection class introductory cases Wulin expert class
How to extract dates from web pages?
Resolving the conflict problem of the flutter Library
Flutter: Unsupported value: false/true
Flutter: Unsupported value: false/true
Reduce the pip to the specified version (upgrade the PIP through CMP and reduce it to the original version)