什么是设计模式
https://en.wikipedia.org/wiki/Design_Patterns
https://en.wikipedia.org/wiki/Software_design_pattern
我们说的 23 中设计模式,是来自一本 1994 年出版的书:《Design Patterns: Elements of Reusable Object-Oriented Software》。
这本书的中文名字叫:《设计模式:可复用面向对象软件的基础》。
写这本书的四位作者,被人成为 GoF(Gang of Four),也就是四人帮的意思(因为我们这边的关系,这个词在西方也比较著名,所以...)。
其中定义了设计模式,就是类似的问题的一种解决方案,或者说优秀的设计风格、编码风格,提升代码重用,同时实现高内聚、低耦合,让程序会更加可理解,更加可拓展,更加可维护。
- 一般谈到设计模式,都是在面向对象编程。但是我理解这是一种编程思想,和面向对象并不是强绑定关系。这点需要更多的思考和总结。
- 这里只研究 GoF 的 23 种设计模式,不是说这就是设计模式的全部,这个可能每个人有不同的看法。
- 根据维基百科信息,GoF 后来想重新整理这本书,重新分类,增删一些模式,但是最终没有达成一致。
- 根据维基百科信息,有人认为本书提到的设计模式只是语言特性缺失,在其他语言中,部分模式是不需要的。
- 就好像我们教材上基于 C 语言的数据结构,有部分在现代语言中是不需要开发者去编码实现一样,编译器做的很好了。
六大原则 SOLID
- 单一职责原则(Single Responsibility Principle)
- 开闭原则(Open Closed Principle)
- 里氏替换原则(Liskov Substitution Principle)
- 迪米特法则(Law of Demeter),又叫:最少知识法则(Least Knowledge Principle)
- 接口隔离原则(Interface Segregation Principle)
- 依赖倒置原则(Dependence Inversion Principle)
有些资料中还加入了一个:合成复用原则 Composite/Aggregate Reuse Principle,减少继承,多用聚合。
- https://zhuanlan.zhihu.com/p/110130347
- https://cloud.tencent.com/developer/article/1650116
模式清单
创建型模式 Creational
- 工厂模式 Factory Pattern
- 问题:
- 方案:
- 效果:
- 抽象工厂模式 Abstract Factory Pattern
- 问题:
- 方案:
- 效果:
- 单例模式 Singleton Pattern
- 问题:
- 方案:
- 效果:
- 建造者模式 Builder Pattern
- 问题:
- 方案:
- 效果:
- 原型模式 Prototype Pattern
- 问题:
- 方案:
- 效果:
结构型模式 Structural
- 代理模式 Proxy Pattern
- 问题:
- 方案:
- 效果:
- 适配器模式 Adapter Pattern
- 问题:
- 方案:
- 效果:
- 桥接模式 Bridge Pattern
- 问题:
- 方案:
- 效果:
- 组合模式 Composite Pattern
- 问题:
- 方案:
- 效果:
- 装饰器模式 Decorator Pattern
- 问题:
- 方案:
- 效果:
- 外观模式 Facade Pattern
- 问题:
- 方案:
- 效果:
- 享元模式 Flyweight Pattern
- 问题:
- 方案:
- 效果:
行为型模式 Behavioral
- 责任链模式 Chain of Responsibility Pattern
- 问题:
- 方案:
- 效果:
- 命令模式 Command Pattern
- 问题:
- 方案:
- 效果:
- 解释器模式 Interpreter Pattern
- 问题:
- 方案:
- 效果:
- 迭代器模式 Iterator Pattern
- 问题:
- 方案:
- 效果:
- 中介者模式 Mediator Pattern
- 问题:
- 方案:
- 效果:
- 备忘录模式 Memento Pattern
- 问题:
- 方案:
- 效果:
- 观察者模式 Observer Pattern
- 问题:
- 方案:
- 效果:
- 状态模式 State Pattern
- 问题:
- 方案:
- 效果:
- 策略模式 Strategy Pattern
- 问题:
- 方案:
- 效果:
- 模板模式 Template Pattern
- 问题:
- 方案:
- 效果:
- 访问者模式 Visitor Pattern
- 问题:
- 方案:
- 效果:
参考资料与拓展阅读
- 维基百科(en),并发模式 Concurrency pattern
- 维基百科(en),架构模式 Architectural pattern
- 维基百科(en),Enterprise Integration Patterns,关于企业应用程序集成和面向消息的中间件的 65 种模式
- 维基百科(en),Pattern-Oriented Software Architecture,面向模式软件架构