接口设计原则
单一职责原则 SRP
Single Responsibility Principle
There should never be more than one reason for a class to change.
应该有且只有一个原因引起一个类的变更
在实际开发过程中,适当地违背单一职责原则是可以一定程度上提高开发效率
里氏替换原则 LSP
Liskov Substitution Principle
Objects of a superclass shall be replaceable with objects of its subclasses without breaking the application.
That requires the objects of your subclasses to behave in the same way as the objects of your superclass.
子类必须完全实现父类方法
子类可以有自己的属性和方法
覆盖或实现父类方法时,输入参数可以放大
覆盖或实现父类方法时,输出结果可以缩小
什么是输入参数可以放大
父类A有方法 m(HashMap),子类B有方法 m(Map),这就是输入参数放大,即在没有重写父类方法时,不允许调用子类方法
假设父类A有方法 m(Map),子类B有方法 m(HashMap),实例化 A a = new A();执行方法 a.m(new HashMap()) 会在没有重写方法时调用了子类方法
什么是输出结果可以缩小
如果父类的方法返回值类型时T,子类重写或重载父类方法的返回值类型是S,那么要求S必须小于等于T
依赖倒置原则 DIP
Dependence Inversion Principle
High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces).
Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.
高层模块不应该依赖底层模块,二者都应该依赖其抽象
抽象不应该依赖细节,细节应该完全依赖于抽象
Test-Driven-Development 测试驱动要求先写测试,测试通过再写实现类
构造函数传递依赖对象
Setter 方法传递依赖对象
接口声明依赖对象
最佳实践
每个类尽量有接口或抽象类,或者都有接口和抽象类
变量的表面类型尽量是接口或抽象类
任何类都不应该从具体类派生
不要覆盖基类的写法
结合里氏替换原则
接口隔离原则 ISP
Interface Segregation Principle
Clients should not be forced to depend upon interfaces that they do not use.
The dependcy of one class to another one should depend on the smallest possible interface.
建立单一接口,不要臃肿庞大
接口要小,高内聚,定制化服务
迪米特法则 LOD(Least Knowledge Principle LKP)
Law of Demeter
- Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
- Each unit should only talk to its friends; don't talk to strangers.
- Only talk to your immediate friends.
底耦合,高封装,慎用Serializable
开闭原则 OCP
Open Closed Principle
software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification
对扩展开放,对修改关闭
类,模块,功能函数
睁开眼,书在面前 闭上眼,书在心里