Java 23种设计模式之装饰器模式
2018-01-01 18:52
453 查看
1. 概念
动态的给一个对象添加一下额外的职责,就增加功能来说, 装饰模式比生成子类更加灵活。
2. 创建Person对象
public class Person { private String name; public Person(){} public Person(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void show(){ System.out.println("装扮的 "+name); } }
3. 创建装饰类对象
public class PersonDecorator extends Person { protected Person person; public void decorate(Person person){ this.person = person; } public void show(){ if(person != null){ person.show(); } } }
4. 创建具体装饰类对象
1. public class Sneakers extends PersonDecorator{ @Override public void show() { System.out.print("破球鞋 "); super.show(); } } 2. public class Suit extends PersonDecorator{ @Override public void show() { System.out.print("西装 "); super.show(); } } 3. public class Tie extends PersonDecorator{ @Override public void show() { System.out.print("领带 "); super.show(); }
}
4.
public class LeatherShoes extends PersonDecorator{
@Override public void show() { System.out.print("皮鞋"); super.show(); } } 等等.....
5. 测试类
@org.junit.Test public void test(){ Person p = new Person("zlc"); System.out.println("第一种装扮 :"); //球鞋 Sneakers sneakers = new Sneakers(); //T恤 TShirt tShirt = new TShirt(); //垮裤 Trouser trouser = new Trouser(); sneakers.decorate(p); trouser.decorate(sneakers); tShirt.decorate(trouser); tShirt.show(); System.out.println(); System.out.println("第二种装扮 :"); //皮鞋 LeatherShoes leatherShoes = new LeatherShoes(); //领带 Tie tie = new Tie(); //西装 Suit suit = new Suit(); leatherShoes.decorate(p); tie.decorate(leatherShoes); suit.decorate(tie); suit.show(); System.out.println(); }
6.小结
装饰模式是为已有的功能动态的添加更多功能的一种方式 把类中的装饰功能从类中搬移去除,这样可以简化原有的类,可以有效的把 类的核心职责和装饰功能区分开了,而且可以去除类中重复的装饰逻辑。
相关文章推荐
- java23种设计模式--装饰模式(decorator)
- java23种设计模式之装饰器模式
- JAVA开发的23种设计模式之 — 装饰器模式 && 代理器模式
- Java开发中的23种设计模式详解----装饰模式(Decorator)
- java23种设计模式之装饰模式(Decorator)
- 23种设计模式java实例代码之装饰模式
- Java23种设计模式——装饰模式
- Java开发中的23种设计模式之七:装饰模式(Decorator)
- JAVA的23种设计模式---装饰模式
- java23种常用设计模式之装饰模式(Decorator)
- JAVA 设计模式之装饰模式
- Java设计模式---装饰模式(Decorator)
- java关于23种设计模式的有趣见解[转]
- Java23种设计模式学习笔记【目录总贴】
- Java开发中的23种设计模式详解
- Java设计模式百例 - 装饰器模式
- 源自老毕Java基础教程--装饰设计模式
- Java开发中的23种设计模式详解(转)
- java的23种设计模式极其详解
- Java开发中的23种设计模式详解