简写 | 原则 | 中文 | 备注 |
---|---|---|---|
SRP | The Single Responsibility Principle | 单一职责原则 | 一个类,只干自己件事 |
OCP | The Open-Closed Principle | 开闭原则 | 不会对现有的东西造成影响, 使用接口 |
LSP | The Liskov Substitution Principle | 里氏替换原则 | 子替父也是可行的 |
DIP | The Dependency Inversion Principle | 依赖反转原则 | 依赖接口,服务上层 |
ISP | The Interface Segregation Principle | 接口隔离原则 | 为了避免过度使用接口,对接口瘦身 |
0. 总结
以上5个原则里面,除了LSP这个,其他几个其实都是相互关联的, 例如,你如果不SRP的话, ISP就不好搞
- 不干太多的事 -> SRP
- 不打扰前任 -> OCP
- 我儿子来也行 -> LSP
- 我要的,你提供 -> DIP
- 接口虽好,不要贪杯 -> ISP
1. SRP
A class should have only one reason to change
Responsibility: a reason to change
坏 | 好 |
---|---|
| |
| |
2. OCP
Software entities (classes, modules, functions, etc) should be open for extension, but closed for modification
坏 | 好 |
---|---|
| |
| |
3. LSP
Subtypes must be substitutable for their base types
IS a is about Behavior
Design by Contract
Specifying Contract in UnitTest
4. 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
坏 | 好 |
---|---|
| |
| |
Depend on Abstractions
5. ISP
There are objects that require noncohesive interfaces; however, it suggests that client should not know about them as a single class. Instead
clients should know about abstract base classes that have cohesive interfaces
坏 | 好 |
---|---|
| |
| |
ref: Agile Software Development Principles Patterns And Practices: section 2
网友评论