装饰者模式html
动态地给一个对象添加一些额外的职责,就增长功能来讲,装饰模式比生成子类更加灵活.java
场景:设计模式
经过给小明穿衣服来演示装饰者模式ide
被装饰的人类
/** * 被装饰的人 */ public class Person { /** * 名字 */ private String name; /** * 构造函数 * * @param name */ public Person(String name) { this.name = name; } public Person() { } public void show() { System.out.println(MessageFormat.format("装扮的{0}", this.name)); } }
服饰类
/** * 服饰类 */ public class Finery extends Person { /** * 成员 */ protected Person component; /** * 打扮 * * @param component */ public void decorate(Person component) { this.component = component; } @Override public void show() { if (this.component != null) { this.component.show(); } } }
服饰子类函数
/** * T恤类 */ public class TShirts extends Finery { @Override public void show() { System.out.println("大致恤 "); super.show(); } } /** * 垮裤类 */ public class BigTrouset extends Finery { @Override public void show() { System.out.println("垮裤 "); super.show(); } } /** * 破鞋子类 */ public class BrokenShoes extends Finery { @Override public void show() { System.out.println("破鞋子 "); super.show(); } }
调用:post
/** * 大话设计模式(java版) * 第三章:装饰者设计模式 */ public class DecoratorDemo { public static void main(String[] args) { Person person=new Person("小明"); System.out.println("装扮风格: "); //T恤 TShirts tShirts=new TShirts(); //垮裤 BigTrouset bigTrouset =new BigTrouset(); //破鞋子 BrokenShoes brokenShoes=new BrokenShoes(); //装饰小明 tShirts.decorate(person); //装饰T恤 bigTrouset.decorate(tShirts); //装饰垮裤 brokenShoes.decorate(bigTrouset); brokenShoes.show(); } }
结果this
装扮风格:
破鞋子
垮裤
大致恤
装扮的小明
解析:url
1.须要把所需的功能按正确的顺序串联起来进行控制.spa
2.装饰模式是为已有功能动态的添加更多功能的一种方式.设计
3.当系统须要新的功能的时候,是向旧的类中添加新的代码.这样新加的代码一般装饰了原有类的核心职责或主要行为.
4.再主类中加入了新的字段,新的方法和新的逻辑,从而增长了主类的复杂度,二这些新加入的东西仅仅是为了知足一些只在某种特定状况下才会执行的特殊行为须要,装饰模式却提供了一个很是好的解决方案,他吧每一个要装饰的功能放在单独的类中,并让这个类包装他所要装饰的对象,所以,当须要执行特殊行为时,客户端代码就能够在运行时根据须要有选择、按顺序地使用装饰功能包装对象.
5.装饰模式的优势,把类中的装饰功能从类中搬移去除,这样能够简化原有的类,有效的把类的核心职责和装饰功能区分开了,并且能够去除相关类中重复的装饰逻辑.