装饰模式(Decorator):动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
装饰模式是为已有功能动态地添加更多功能的一种方式。装饰模式提供了非常好的解决方案,它把每个装饰功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象。
装饰模式的优点:把类中的装饰功能从类中搬移去除,这样可以简化原有的类。有效地把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。
People.java类
package decorate; public class People{ private String name; public People() { } public People(String name) { this.name = name; } public void operation() { System.out.println("开始装饰:"+name); } }
Finery.java类
package decorate; public class Finery extends People{ private People people; public void decorate(People people) { this.people = people; } public void operation(){ people.operation(); } }
TshirtFinery.java类
package decorate; public class TshirtFinery extends Finery { @Override public void operation() { super.operation(); this.show(); } public void show(){ System.out.println("大T衫"); } }
BigTrouserFinery.java类
package decorate; public class BigTrouserFinery extends Finery { @Override public void operation() { super.operation(); this.show(); } public void show(){ System.out.println("大裤衩"); } }
ShoeFinery.java类
package decorate; public class ShoeFinery extends Finery { @Override public void operation() { super.operation(); this.show(); } public void show(){ System.out.println("长袜子"); } }
Business.java类
package decorate; public class Business { public static void main(String[] args) { People p = new People("桂清"); TshirtFinery t = new TshirtFinery(); BigTrouserFinery b = new BigTrouserFinery(); ShoeFinery s = new ShoeFinery(); t.decorate(p); b.decorate(t); s.decorate(b); s.operation(); } }