• 6个设计原则


    1. 单一职责原则(Single Responsibility Principle, SRP)

        应该有且仅有一个原因引起类的变更。There should never be more than one reason for a class to change.

        可能会引起类的剧增,过细的划分人为地增加了系统的复杂性,需要因项目和环境而变通。这一原则很难在项目中体现。

    2. 里氏替换原则(Liskov Substitution Principle, LSP)

        If for each object o1 of type S, there is a object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substitued for o2 then S is a subtype of T.

        在类中调用其他类时务必使用父类或接口,如果不能使用父类或接口,则说明类的设计已经违背了LSP原则。

        如果子类不能完整地实现父类的方法,建议断开父子继承关系,采用依赖、聚集、组合等关系替代。

        子类中方法的参数必须与父类中被覆写的方法的参数相同或更宽松,子类覆写或实现父类的方法时输出结果类型范围小于等于父类的输出结果类型。

        里氏替换原则的目的是增强程序健壮性,增加子类时与原系统兼容,不至于引起混乱。

    3. 依赖倒置原则(Dependence Inversion Principle, DIP)

        High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon detials. Details should depend upon abstractions.

        每个类尽量都有接口或抽象类,或者两者都有。

        变量的表面类型尽量是接口或抽象类。

        任何类都不应该从具体类派生。(并不绝对,可依项目情况变通)

        尽量不要覆写基类的方法。

    4. 接口隔离原则

        Clients should not be forced to depend upon interfaces that they don't user.

        The dependency of one class to another one should depend on the smallest possibile interface.

        接口要尽量小,不要臃肿,但不要无限设计,要符合单一职责原则。接口要高内聚。

        一个接口只服务于一个子模块或业务逻辑。

    5. 迪米特法则(Law of Demeter, LoD; Least Knowledge Principle, LKP)

        一个对象应该对自己需要耦合或调用的类知道得最少,只与直接朋友通信。出现在成员变量、方法的输入输出参数的类称为朋友类,出现在方法体内的类不算。

        尽量不对外公布太多的public方法和非静态public变量。

        谨慎使用Serializable。

    6. 开闭原则

        Software entities like classes, modules and functions should be open for extension but closed for modifications.

        对扩展开放,对修改关闭。  

        

  • 相关阅读:
    jquery operate
    ujs
    图标站
    rails foreign key
    feedback product from uservoice
    秒杀网
    short url
    rails nil blank
    paperclip imagemagic api &paperclip relevent
    类似优米网
  • 原文地址:https://www.cnblogs.com/ylty/p/6059448.html
Copyright © 2020-2023  润新知