`
897371388
  • 浏览: 528422 次
文章分类
社区版块
存档分类
最新评论

学习设计模式之禅——6大设计原则

 
阅读更多

一年前就拥有秦小波写的《设计模式之禅》,由于时间和项目经验原因,一直都没有仔细阅读,最近抽时间学习。

里面首先介绍的是程序设计的6大原则。


1、单一职责原则(Single Responsibility Principle 简称是SRP),接口、类、方法尽量做到单一。

2、里氏替换原则(If for each object o1 of type S there is an 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 substituted o2 then S is a subtype of T,如果对每个类型为S的对象o1,都有类型为T的对象o2,使得以T定义的所有程序P在所有的对象o1都代换成o2时,程序P的行为没有发生变化,那么类型S是类型T的子类型)

3、依赖倒置原则(Dependence Inversion Principle, DIP),原始定义,High level modeules should not depend upon low level modules,Both should depend upon abstractions, Abstractions should not depend upon details, Detail should depend upon abstractions.翻译过来包含三层含义:

1)高层模块不应该依赖底层模块,两者都应该依赖其抽象。

2)抽象不应该依赖细节。

3)细节应该依赖抽象。

依赖倒置原则在Jave语言中的表现就是:1)模块之间的依赖通过抽象发生,实现类之类不发生直接的依赖关系,其依赖关系是通过接口或抽象类产生的。2)接口和抽象类不依赖于实现类。3)实现类依赖接口或抽象类。

更加精简的定义就是“面向接口编程”——OOD(Object-Oriented Design,面向对象设计的精髓之一)。

4、接口隔离原则,有两种定义,1)Clients should not be forced ti depend upon interfaces that they don't use(客户端不应该依赖他不需要的接口)

2)The dependency of one class to anorher one should depend on the smallest possible interfaces(类间的依赖关系应该建立在最小的接口上)

5、迪米特法则(Law of Demeter, LoD),也称为最少知识原则(Least Knowlege Principle, LKP),一个对象应该对其他对象有最少的了解,通俗的讲,一个类应该对自己需要偶合或调用类知道得最少,你(被偶合或调用的类)内部是如何复杂都和我没有关系,那是你的事情,我就知道几提供了这么多的public方法,我就调用这么多,其他的我一概不关心。

6、开闭原则(Software entities like classes ,modules and fuctions should be open for extenstion but closed for modification),一个软件实体如类、模块和函数应该对扩展开放,对修改关闭


以上就是程序设计的6大原则,后面会慢慢体会到其的奥秘。


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics