现在的位置: 首页 > 综合 > 正文

面向对象的六大设计原则

2013年12月05日 ⁄ 综合 ⁄ 共 1424字 ⁄ 字号 评论关闭

 

面向对象的六大设计原则:

1.Single Responsiblility Principle 单一职责原则
There should never be more than one reason for a class to change

应该做到有且仅有一个原因引起类的变更。
接口尽量要单一
2.Open Closed Principle 开闭原则

Software entities like classes, modules and functions should be open for extension but closed for modifications.
主要是:对扩展开发,对修改关闭
注意事项:
  1)抽象约束
   由于接口或抽象是两个模块之间的一种契约,因此在接口或抽象类中,对扩展进行边界限定,不允许出现在接口或抽象类中不再的public方法;
参数类型,引用对象尽量使用接口或者抽象类,而不是实现类;抽象层尽量保持稳定。
  2)元数据(metadata)控制模块行为
  尽量采用配置文件来控制模块的行为
  3)封装变化
  将相同的变化封装到一个接口或抽象类中;将不同的变化封装到不同的接口或抽象类中。

3.Liskov Substitution Principle 里氏替换原则
Functions that use pointers or references to base classes must be able to use object of derived classed without knowing it.

主要是对OOP中,继承进行了约束:
所有引用基类的地方必须能够透明地使用其子类的对象
1.子类必须完全实现父类的方法,调用时,务必使用父类或接口
2.覆盖或实现父类的方法时,输入参数可以被放大,也就是说,子类的输入参数类型要宽于父类的类型覆盖范围
3.覆写或实现父类的方法时,输出结果可以被缩小

注意:子类拥有父类的所有属性和方法
4.Law of Demeter 迪米特法则

也称为最少知识原则 Least Knowledge Principle.
对类的低耦合提出了要求,要求类“羞涩”一点,尽量不要对外公布太多的public方法和非静态的public变量,尽量内敛,多使用
private,packag-private

5.Interface Segregation Principle 接口隔离原则
The dependency of one class to another one should depend on the smallest possible interface.

接口隔离原则:
1.接口要尽量的小 (优先满足单一职责)
2.尽量小的使用public方法。

接口分为实例接口Object Interface 和类接口 class interface

6.Dependence Inversion Principle 依赖倒置原则

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

也就说:
1.高层模块不应该依赖于低层模块,两者都应该依赖其抽象。
2.抽象不应该依赖于细节
3.细节应该依赖于抽象

通过抽象可以使系统中的各个类或模块的实现彼此独立,不相互影响,实现模块间的松耦合。
但注意,JDK规定,使用clone方法时,必须使用实现类。

抱歉!评论已关闭.