单一职责原则
(Single Responsibility Principle)
对类来说的,即一个类应该只负责一项职责。
问题演示
、存在问题,职责不单一
1 | public class SingleResponsibility1 { |
解决方法
1)、类的职责单一
1 | public class SingleResponsibility2 { |
2)、方法职责单一
、只有类中方法数量足够少,可以在方法级别保持单一职责原则
1 | public class SingleResponsibility3 { |
注意事项
1)、降低类的复杂度,一个类只负责一项职责。
2)、提高类的可读性,可维护性
3)、降低变更引起的风险
4)、通常情况下,我们应当遵守单一职责原则,只有逻辑足够简单,才可以在代码级违反单一职责原则;
只有类中方法数量足够少,可以在方法级别保持单一职责原则
接口隔离原则
(Interface Segregation Principle)
客户端不应该依赖它不需要的接口,即一个类对另一个类的依赖应该建立在最小的接口上。
问题演示
对不需要的方法也进行了实现
1 | public class Segregation1 { |
解决方法
抽取出来公共的方法作为接口,把使用到的接口尽量减小
1 | public class Segregation1 { |
依赖倒转原则
(Dependence Inversion Principle)
1)、高层模块不应该依赖低层模块,二者都应该依赖其抽象
2)、抽象不应该依赖细节,细节应该依赖抽象(面向接口编程)
3)、类中方法参数应该是接口,而不是具体的实现类。
问题演示
把参数写死了,如果想用来发微信,就比较难做
1 | public class DependecyInversion { |
解决方法
使用面向接口编程,不要用具体的实现类,而是使用接口
1 | public class DependecyInversion { |
三种依赖传递
1)、普通方法参数传递
1 | public class DependencyPass { |
2)、构造方法参数传递
1 | public class DependencyPass { |
3)、setter方法参数传递
1 | public class DependencyPass { |
注意事项
1)、低层模块尽量都要有抽象类或接口,或者两者都有,程序稳定性更好.
2)、变量的声明类型尽量是抽象类或接口, 这样我们的变量引用和实际对象间,就存在一个缓冲层,利于程序扩展和优化
3)、继承时遵循里氏替换原则
里氏替换原则
(Liskov Substitution Principle)
1)、子类出现的地方可以被子类替换,在替换后依然保持原功能。
2)、在使用继承时,遵循里氏替换原则,在子类中尽量不要重写父类的方法
3)、里氏替换原则告诉我们,继承实际上让两个类耦合性增强了,在适当的情况下,可以通过聚合,组合,依赖 来解决问题。
问题演示
B中fun2调用了fun1,但是这个fun1重写了父类A中的fun1
1 | public class Liskov { |
解决方法
把A和B都继承基类Base,此时A和B中都有fun1,但是不存在重写的关系了。
此时B中的fun2中调用了fun1,就与A无关系了,从而降低了耦合。
如果B中的fun3实在想使用A中的fun1方法,可以在B中创建成员变量A a,在fun3中使用a.fun1来调用A中的fun1方法
1 | public class Liskov { |
开闭原则
(Open Close Principle)
是编程中最基础、最重要的设计原则。所有原则都是根据这个来设计的。
对扩展开放,对修改关闭。即:增加新功能,不改变原有代码。
问题演示
如果想新增三角形,1.增加类Triangle,2.增加方法drawTriangle,3.增加判断s.m_type == 3
1 | public class Ocp { |
解决方法
面向接口编程,增加新功能,只需要新增一个类即可。
方法参数使用接口,而不是具体的实现类。
把创建 Shape 类做成抽象类,并提供一个抽象的 draw 方法,让子类去实现即可,
这样我们有新的图形种类时,只需要让新的图形类继承 Shape,并实现 draw 方法即可
1 | public class Ocp { |
迪米特法则
(Law Of Demeter)
类与类交互时,在满足功能要求的基础上,传递的数据量越少越好。因为这样可能降低耦合度。
1)、一个对象应该对其他对象保持最少的了解
2)、类与类关系越密切,耦合度越大
3)、迪米特法则(Demeter Principle)又叫最少知道原则,即一个类对自己依赖的类知道的越少越好。也就是说,对于被依赖的类不管多么复杂,都尽量将逻辑封装在类的内部。对外除了提供的 public 方法,不对外泄露任何信息
4)、迪米特法则还有个更简单的定义:只与直接的朋友通信
5)、直接的朋友:每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系,我们就说这两个对象之间是朋友关系。
耦合的方式很多,依赖,关联,组合,聚合等。其中,我们称出现成员变量
,方法参数
,方法返回值
中的类为直接的朋友,而出现在局部变量中的类不是直接的朋友。也就是说,陌生的类最好不要以局部变量的形式出现在类的内部。
问题演示
在SchoolManager类中printAllEmployee方法中使用了局部变量List<CollegeEmployee> list1
,而CollegeEmployee不是SchoolManager的直接朋友。
1 | import java.util.ArrayList; |
解决方法
把打印CollegeEmployee的打印,作为一个方法封装到CollegeManager类中。
1 | import java.util.ArrayList; |
注意事项
1)、迪米特法则的核心是降低类之间的耦合
2)、但是注意:由于每个类都减少了不必要的依赖,因此迪米特法则只是要求降低类间(对象间)耦合关系, 并不是要求完全没有依赖关系
合成复用原则
(Composite Reuse Principle)
尽量使用合成/聚合达到复用,尽量少用继承。原则: 一个类中有另一个类的对象。
七大原则总结
1)、找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起。
2)、针对接口编程,而不是针对实现编程。
3)、为了交互对象之间的松耦合设计而努力