面向对象设计原则

一、开放封闭原则(Open Close Principle)

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

即: 一个软件实体如类、模块和函数应该对扩展开放,对修改关闭。

二、单一职责原则(Single Responsibility Principle)

A class should have a single responsibility, where a responsibility is nothing but a reason to change.

即: 一个类只允许有一个职责,即只有一个导致该类变更的原因。

三、依赖倒置原则(Dependency Inversion Principle)

  • Depend upon Abstractions. Do not depend upon concretions.
  • Abstractions should not depend upon details. Details should depend upon abstractions
  • High-level modules should not depend on low-level modules. Both should depend on abstractions.

即:

  • 依赖抽象,而不是依赖实现。
  • 抽象不应该依赖细节;细节应该依赖抽象。
  • 高层模块不能依赖低层模块,二者都应该依赖抽象。

四、接口分离原则(Interface Segregation Principle)

Many client specific interfaces are better than one general purpose interface.

即: 多个特定的客户端接口要好于一个通用性的总接口。

五、迪米特法则(Law of Demeter)

You only ask for objects which you directly need.

即: 一个对象应该对尽可能少的对象有接触,也就是只接触那些真正需要接触的对象。

迪米特法则也叫做最少知道原则(Least Know Principle), 一个类应该只和它的成员变量, 方法的输入, 返回参数中的类作交流, 而不应该引入其他的类(间接交流)。

六、里氏替换原则(Liskov Substitution Principle)

In a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e. an object of type T may be substituted with any object of a subtype S) without altering any of the desirable properties of the program (correctness, task performed, etc.)

即: 所有引用基类的地方必须能透明地使用其子类的对象, 也就是说, 子类对象可以替换其父类对象, 而程序执行效果不变。

原文地址:https://www.cnblogs.com/fanlumaster/p/14010405.html