代码设计原则笔记

2020-07-02  本文已影响0人  天之見證
简写 原则 中文 备注
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就不好搞

  1. 不干太多的事 -> SRP
  2. 不打扰前任 -> OCP
  3. 我儿子来也行 -> LSP
  4. 我要的,你提供 -> DIP
  5. 接口虽好,不要贪杯 -> ISP

1. SRP

A class should have only one reason to change

Responsibility: a reason to change

modem_java.PNG
sep_modem.PNG

2. OCP

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

not_oc.PNG
oc.PNG

3. LSP

Subtypes must be substitutable for their base types

rectangle_square_lsp.PNG

IS a is about Behavior

Design by Contract

Specifying Contract in UnitTest

4. DIP

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions
  2. Abstractions should not depend on details. Details should depend on abstractions
no_dip.PNG
dip.PNG

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

no_isp.PNG
isp.PNG

ref: Agile Software Development Principles Patterns And Practices: section 2

上一篇 下一篇

猜你喜欢

热点阅读