代码设计基础知识小结

85 阅读1分钟

SOLID原则

面向对象 class 设计的五条原则。他们是设计 class 结构时应该遵守的准则和最佳实践。

  • S:Single Responsibility principle 单一职责原则,一个类应该只有一个引起它变化的原因。
    • There should never be more than one reason for a class to change.
    • In other words, every class should have only one responsibility.
  • O:Open–closed principle 开闭原则,类应该对扩展开放对修改关闭。
    • Software entities ... should be open for extension, but closed for modification.
  • L:Liskov substitution principle 里氏替换,应用程序中任何父类对象出现的地方,我们都可以用其子类的对象来替换,并且可以保证原有程序的逻辑行为和正确性
    • Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.
    • 里氏替换主要说明了针对类继承的规则:如果继承是为了代码复用,则共享的父类方法应该保持不变,子类增加新的方法来扩展功能。如果继承是为了多态,多态的前提就是覆盖并重新定义父类方法,则应该将父类定义为抽象类。
  • I:Interface segregation principle 接口隔离,客户端只依赖于它必须的接口,接口中的方法尽量少
    • clients should not be forced to depend upon interfaces that they do not use
  • D:Dependency inversion principle 依赖倒置,针对接口编程,模块之间依赖抽象
    • Dependency inversion principle (DIP) states to depend upon abstractions, not concretes
  • 参考:cloud.tencent.com/developer/a…