- 4
- 0
- 约9.9千字
- 约 18页
- 2016-05-04 发布于重庆
- 举报
设计模式复习
单一职责原则(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
- 2023年度十大热点人物的素材解读与运用-2024年高考语文作文热点素材积累运用与(全国通用).pdf
- 格力室外机中央空调价格表.pdf
- 2026上半年贵州事业单位联考贵州省交通运输厅招聘84人备考题库完整答案详解.docx
- 2026上半年贵州事业单位联考贵州传媒职业学院招聘12人备考题库附参考答案详解(达标题).docx
- 2026上半年贵州事业单位联考贵州省住房和城乡建设厅招聘16人备考题库含答案详解(培优).docx
- 2026上半年贵州事业单位联考玉屏侗族自治县招聘41人备考题库及答案详解(夺冠系列).docx
- 通信原理实验2数字频带传输系统实验.pdf
- 2026上半年贵州事业单位联考贵州医科大学第二附属医院招聘22人备考题库含答案详解(能力提升).docx
- 2026上海复旦大学计算力学与人工智能交叉研究院(筹)招聘专任研究员2人备考题库完整答案详解.docx
- 2026上半年贵州事业单位联考贵州民族大学招聘52人备考题库附参考答案详解(研优卷).docx
原创力文档

文档评论(0)