接口设计原则
单一职责原则 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
对扩展开放,对修改关闭
类,模块,功能函数
作者:BigBender
出处:https://www.cnblogs.com/BigBender/p/15847166.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
2021-01-27 Git介绍
2020-01-27 向量的概念和运算