天天看點

設計模式第七堂課

1. OCP (Open Close Principle)

A. Software entities like classes, modules and functions should be open for extension but 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

繼續閱讀