设计模式第七堂课

来源:互联网 发布:黄狮精 知乎 编辑:程序博客网 时间:2024/06/04 18:48

1. OCP (Open Close Principle)

A. Software entities like classes, modules and functions should beopen for extensionbut closed for modifications

B. The design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code

C. The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged

1) usage

Being applied in those area which are most likely to be changed

2) liabilities

Making a flexible design involves additional time and effort spent for it and itintroduce new level of abstraction increasing the complexity of the code


Figure 1 A Design of Violating OCP


Figure 2 A Design of Following OCP


2. DIP (Dependency Inversion Principle) / Hollywood Principle
A. High-level modules should not depend on low-level modules. Both should 
depend on abstractions

B. Abstractions should not depend on details. Details should depend on abstractions

1) liabilities

Using this principle implies an increased effort, will result in more classes andinterfaces to maintain


Figure 3 A Design of Violating DIP


Figure 4 A Design of Following DIP


3. ISP (Interface Segregation Principle)
A. Clients should not be forced to depend upon interfaces that they don't use

1) liabilities

Requiring additional time and effort spent to apply it during the design timeand increase the complexity of code


Figure 5 A Design of Violating ISP


Figure 6 A Design of Following ISP


4. SRP (Single Responsibility Principle)
A. A class should have only one reason to change

1) liabilities 

Increasing the complexity of code


Figure 7 Sample SRP

5. LSP (Liskov’s Substitution Principle)
A. Derived types must be completely substitutable for their base types
B. This principle is just an extension of the Open Close Principle
C. Making sure that new derived classes are extending the base classes without 
changing their behavior


Figure 8 A Design of Violating LSP


0 0