- 6
- 0
- 约9.9千字
- 约 18页
- 2016-05-04 发布于重庆
- 举报
设计模式6大原则
单一职责原则(Single?Responsibility?Principle)class Animal{
public void breathe(String animal){
System.out.println(animal+呼吸空气);
}
}
public class Client{
public static void main(String[] args){
Animal animal = new Animal();
animal.breathe(牛);
animal.breathe(羊);
animal.breathe(猪);
}
}
运行结果:
牛呼吸空气
羊呼吸空气
猪呼吸空气Terrestrial,水生动物Aquatic,代码如下:
class Terrestrial{
public void breathe(String animal){
System.out.println(animal+呼吸空气);
}
}
class Aquatic{
public void breathe(String animal){
System.out.println(animal+呼吸水);
}
}
public class Client{
public static void main(String[] args){
Terrestrial terrestrial = new Terrestrial();
terrestrial.breathe(牛);
terrestrial.breathe(羊);
terrestrial.breathe(猪);
Aquatic aquatic = new Aquatic();
aquatic.breathe(鱼);
}
}牛呼吸空气
羊呼吸空气
猪呼吸空气
鱼呼吸水class Animal{
public void breathe(String animal){
if(鱼.equals(animal)){
System.out.println(animal+呼吸水);
}else{
System.out.println(animal+呼吸空气);
}
}
}public class Client{
public static void main(String[] args){
Animal animal = new Animal();
animal.breathe(牛);
animal.breathe(羊);
animal.breathe(猪);
animal.breathe(鱼);
}
}breathe方法,而对原有代码的修改会对调用“猪”“牛”“羊”等相关功能带来风险,也许某一天你会发现程序运行的结果变为“牛呼吸水”了。这种修改方式直接在代码级别上违背了单一职责原则,虽然修改起来最简单,但隐患却是最大的。还有一种修改方式:
class Animal{
public void breathe(String animal){
System.out.println(animal+呼吸空气);
}
public void breathe2(String animal){
System.out.println(animal+呼吸水);
}
}
public class Client{
public static void main(String[] args){
Animal animal = new Animal();
animal.breathe(牛);
animal.breathe(羊);
animal.breathe(猪);
animal.breathe2(鱼);
}
}里氏替换原则(Liskov?Substitution?Principle)如果对每一个类型为 T1的对象 o1,都有类型为 T2 的对象o2,使得以 T1定义的所有程序 P 在所有的对象 o1 都代换成 o2 时,程序 P 的行为没有发生变化,那么类型 T2 是类型 T1 的子类型。所有引用基类的地方必须能透明地使用其子类的对象。class A{
public int func1(int a, int b){
return a-b;
}
}
public class Client{
public static void main(String[] args){
A a = new A();
System.out.println(100-50=+a.func1(100, 50));
System.out.println(100-8
您可能关注的文档
- 绍兴市元培中学科学七年级下第一章5-7节.doc
- 绝缘油介电强度测试仪(3杯)卓越电气.doc
- 绝缘电阻吸收比试验.doc
- 绝缘电阻接地电阻实际测量操作应用知识.doc
- 绝缘电阻测试仪使用规范.doc
- 绝缘电阻表检定装置考核报告.doc
- 统计学第4章习题答.doc
- 继电保护设计要求.doc
- 维生素C注射剂稳定性考察.doc
- 继电保护二次侧设计.doc
- 涉诉信访问题解决机制的深度剖析与创新构建.docx
- 构建动态机制,优化鄂尔多斯公务交通补贴——基于精准适配与可持续发展视角.docx
- 构建我国证人保护制度:现状、困境与突破.docx
- 自然暴涨宇宙中重子不对称的机制与前沿探索.docx
- 北五味子体细胞胚发生机制及影响因素的深度解析.docx
- 线性化离散不可压Navier-Stokes方程的矩阵分裂预处理与迭代算法研究:理论、方法与应用.docx
- 论民事诉讼当事人证据收集制度:困境、比较与完善路径.docx
- 建筑公司对项目部对管理办法.pdf
- 生物医学中氧化石墨烯的运用综述-化工论文-化学论文.pdf
- 中等职业学校职业技能大赛比赛操作规程.pdf
最近下载
- 厦门市同安区事业单位招聘考试题目及答案2025.docx VIP
- 公示A646-0059宗地光明新区观光站综合体项目pdf - 重庆市环境保护.PDF
- 草坪学 全套课件.ppt VIP
- 物理-河南普通高中青桐鸣大联考2024-2025学年2025届高三年级上学期1月期末考试试题和答案.docx VIP
- 弱电工程入侵报警系统(含紧急求助)设计方案全.docx VIP
- 《化学催化催化剂》课件.ppt VIP
- 金相检验二级试题.pdf VIP
- 未遂事故管理制度.docx VIP
- 安徽医科大学2021年春季学期护理专业《健康评估》期末考试试卷.docx VIP
- NB_T 20436-2017压水堆核电厂水化学控制.pdf
原创力文档

文档评论(0)