设计模式的五大原则:
- Single Responsibility Principle:单一职责原则
- Open Closed Principle:开闭原则
- Liskov Substitution Principle:里氏替换原则
- Interface Segregation Principle:接口隔离原则
- Dependence Inversion Principle:依赖倒置原则
把这六个原则的首字母联合起来(两个 L 算做一个)就是 SOLID (solid,稳定的),其代表的含义就是这六个原则结合使用的好处:建立稳定、灵活、健壮的设计。下面我们来分别看一下这六大设计原则。
1.单一职责原则(Single Responsibility Principle)
A class should have one, and only one, reason to change. – Robert C Martin
一个类只有一种责任或者说一个类应该只有一个发生变化的原因
2.开放 / 封闭原则(Open / Closed Principle)
Software entities should be open for extension, but closed for modification. – Bertrand Meyer, Object-Oriented Software Construction
一个软件实体,如类、模块和函数应该对扩展开放,对修改关闭
3.里氏替换原则(Liskov Substitution Principle)
由 Barbara Liskov 提出的里氏替换原则粗略地指出,如果两种类型表现出的行为使得调用者无法区分,则这两种类型是可替代的。
在基于类的语言中,里氏替换原则通常被解释为,具有各种具体子类型的抽象基类的规范。 但是 Go 没有类或继承,因此无法根据抽象类层次结构实现替换。
所有引用基类的地方必须能透明地使用其子类对象,子类要实现基类的抽象方法
4.接口隔离原则(Interface Segregation Principle)
Clients should not be forced to depend on methods they do not use. –Robert C. Martin
客户端不应该依赖它不需要的接口。
类间的依赖关系应该建立在最小的接口上。
5.依赖倒置原则(Dependency Inversion Principle)
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. – Robert C. Martin
上层模块不应该依赖底层模块,它们都应该依赖于抽象。
抽象不应该依赖于细节,细节应该依赖于抽象。