Common Principles in Software Engineering软件工程常见几大原则

备注:本文摘自于其他blog.

1、OCP(Open-close principle)开放-封闭原则
     是指一个软件实体应当对扩张开放,对修改关闭。
     Benifits:
    通过扩张已有软件系统,可以提供新的行为,以满足对软件新的需求,使变化中的软件有一定的适应性和灵活性。
    已有软件模块,特别是重要的抽象层模块不能再修改,这使得变化中的软件系统有一定的稳定性和延续性
例如:美猴王大闹天宫的时候,要玉皇大帝让位于他。后太白金星建议,诏安,一则不劳师动众,二则收仙有道也。
2、LSP(liskval substitution principle)里氏代换原则
    指的是子类型(subtype)必须能够替换他们的基类型。??不明白
3、Dependency Inversion Principle依赖倒置原则
            it's better to be dependent to abstract, but not concrete。要依赖于抽象,不要依赖于具体。
简言之,要针对interface编程,不要针对实现编程。
        反面例子:

ToggleSwitch和Light之间couple太紧密!如果Light发生变化,将影响到ToggleSwitch.
改进:

Benefits好处:
在该结构下,ToggleSwitch依赖于抽象类/接口 Light, 而BulbLight和TubeLight继承于LIght.符合开放-封闭原则(对内修改封闭,对外扩展开放)。这样,只要Light不发生改变,ToggleSwitch都不会发生影响。
Deficiency缺点:
如果要控制非Light类的物体,比如电视,就不行了。

继续改进:

conclusion:结论
    using the traditional inherented mechnism, tragedy depends on concrete/details. and this is bad. once the concrete is changed, the tragedy will be forced to change also. Trough Depedency Inversion Policy, we can make that all concrete depend  on abstract, which makes the system more stable and robust.
    使用传统的继承机制,策略依赖于具体细节,这样是很糟糕的。试想一旦细节发生改变,将使得策略也随之改变。通过倒置依赖原则和依赖于抽象的机制,可以使得系统系统更加健壮和稳定。

4、接口隔离原则Interface Segregation Principle
接口隔离原则指的是:使用多个专门的接口比使用单一的总接口要好。换言之,从一个客户类的角度来讲:一个类对另外一个类的依赖性应当是建立在最小接口上的。过于臃肿的接口是对接口的污染。不应该强迫客户依赖于他们不用的方法。
ISP infers that: using more light-weight interfaces are much better than using one big interface. In other words, one class depends on other class should be based on the minimize-interface. too big interface is a kind fo pollution to the interface. we should not force cosumer to depend/ inplement the methods that they don't use them  at all.
实现方法Implemetation:
1使用委托分离接口
2使用多重继承分离接口

5.合成/聚合复用原则(Composite/Aggregate Reuse Principle)    
又称为合成复用原则(Composite Reuse Principle),是指在一个新的对象里面使用一些已有的对象,使之成为新对象的一部分;新对象通过向这些对象的委派达到复用已有功能的目的。
简言之:要尽量使用composite/Aggregation,少使用inheritence.

indenfify the difference with "has-a" and "Is-a"
Is-a means that one is one kind of another one. At the same time ,Has-a means that one has a responsibility of another one.
Is-A 指的是一个类是另外一个类的一种, 而has-a指得是某一个角色具有另外某个角色的责任。导致错误的使用继承而不是合成/聚合的一个常见原因是错误的把has-a 当作is-a.

6 迪米特法则(Law of Demeter, abbreviated as Lod)
    又叫做Least knowledge Princle LKP 最少知识原则,也就是说,一个对象应当对其他对象有尽可能少的了解。与之相关的设计模式Facade模式,Mediator模式。

题外话:
设计模式4个基本元素:
我将其简称为NPSC
N  -> pattern name模式名称
P -> problem问题描述
S ->Solution 解决方案
C ->Consequences 效果


原文地址:https://www.cnblogs.com/Winston/p/1203227.html