Patterns emerge from fundamental principles applied to recurring problems
– Design to interfaces
– Favor composition over inheritance
– Find what varies and encapsulate it
solid principles
– Single Responsibility Principle (应该有且仅有一个原因引起类的变更。简单地说:接口职责应该单一,不要承担过多的职责。)
– Open-Closed Principle (对扩展开放,对修改关闭)
– Liskov Substitution Principle (所有引用基类的地方必须能透明地使用其子类。 这就要求子类的所有相同方法,都必须遵循父类的约定,否则当父类替换为子类时就会出错)
– Interface Segregation Principle (类间的依赖关系应该建立在最小的接口上。简单地说:接口的内容一定要尽可能地小,能有多小就多小。)
– Dependency Inversion Principle (高层模块不应该依赖底层模块,两者都应该依赖其抽象。简单地说,就是说我们应该面向接口编程)
- 单一职责是所有设计原则的基础,开闭原则是设计的终极目标。
- 里氏替换原则强调的是子类替换父类后程序运行时的正确性,它用来帮助实现开闭原则。
- 而接口隔离原则用来帮助实现里氏替换原则,同时它也体现了单一职责。
- 依赖倒置原则是过程式编程与面向对象编程的分水岭,同时它也被用来指导接口隔离原则。
Classification of patterns
- Creational patterns provide object creation mechanisms that increase flexibility and reuse of existing code.
- Structural patterns explain how to assemble objects and classes into larger structures, while keeping these structures flexible and efficient.
- Behavioral patterns take care of effective communication and the assignment of responsibilities between objects.
总共23种
Criticism of patterns
Kludges for a weak programming language **
Usually the need for patterns arises when people choose a programming language or a technology that lacks the necessary level of abstraction. In this case, patterns become a kludge that gives the language much-needed super-abilities.
For example, the Strategy pattern can be implemented with a simple anonymous (lambda) function in most modern programming languages.
Unjustified use
If all you have is a hammer, everything looks like a nail.
参考: refactoring.guru/design-patt… zhuanlan.zhihu.com/p/350291336