How Many Principles of Design Patterns Are There?
Categories:
最早总结的设计模式只有 5 个, 即SOLID
:
单一职责原则 (Single Responsibility Principle, SRP)
:a class should have only one reason to change—i.e., only one responsibility.开闭原则 (Open/Closed Principle, OCP)
:software entities (classes, modules, functions, etc.) should be open for extension but closed for modification; in other words, change should be achieved by extension rather than by modifying existing code.里氏替换原则 (Liskov Substitution Principle, LSP)
:subtypes must be substitutable for their base types—i.e., derived classes must be able to replace their base classes without affecting program correctness.接口隔离原则 (Interface Segregation Principle, ISP)
:clients should not be forced to depend on interfaces they do not use. Large interfaces should be split into smaller, more specific ones so clients only need to know the methods they actually use.依赖倒置原则 (Dependency Inversion Principle, DIP)
:high-level modules should not depend on low-level modules; both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.
后来增加了两个规则, 这些后加的规则相较来说更具体, 更有指导性. 我们从原则解释中可以看到SOLID
描述应该怎么做
, 后加的规则描述优先/最好怎么做
.
合成/聚合复用原则 (Composition/Aggregation Reuse Principle, CARP)
:preference should be given to composition/aggregation over inheritance for reusing code.迪米特法则 (Law of Demeter, LoD)
:an object should have minimal knowledge of other objects—i.e., it should know as little as possible about their internal structure and implementation details.
除了上述提到的常见设计原则外,还有一些其他的设计原则,虽然不如前面提到的那些广为人知,但同样对软件设计和架构有重要的指导作用。 后续提出的这些规则, 有点画蛇添足, 至少我认为它们不反直觉, 不需要深入思考.
最少知识原则 (Principle of Least Knowledge, PoLK)
:also regarded as an extension of the Law of Demeter, it asserts that an object should acquire as little knowledge as possible about other objects. The concept originates from the 1987 “Law of Least Communication” proposed by Patricia Lago and Koos Visser.稳定依赖原则 (Stable Dependencies Principle, SDP)
:this principle holds that a design should ensure stable components do not depend on unstable ones—i.e., components with higher stability should depend less on lower-stability components. The idea stems from in-depth studies of relationships among components in software systems.稳定抽象原则 (Stable Abstraction Principle, SAP)
:in line with the Stable Dependencies Principle, this guideline aligns abstraction with stability: stable components should be abstract, while unstable components should be concrete. It helps maintain both stability and flexibility in the software system.