装饰模式通常是为了在已有功能动态的添加更多功能的一种方式,这些新加的代码通常装饰了原有类的核心职责或者主要行为。而这些新加入的东西仅仅为了满足一些只在某种特定情况下才会执行的特殊行为的需要,装饰器模式将每个要装饰的功能放在单独的类中,并让这个类包装它要装饰的对象。因此,在需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序的使用装饰器功能包装对象。有效地把类的核心职责和装饰功能区分开了。
package DesignPattern.DecoratorPattern;
public class Person {
public Person(){
}
private String name;
public Person(String name){
this.name=name;
}
public void show(){}
}
package DesignPattern.DecoratorPattern;
public class Finery extends Person {
protected Person component;
public void decorate(Person component){
this.component=component;
}
@Override
public void show() {
if(component!=null)
component.show();
}
}
具体装饰类
package DesignPattern.DecoratorPattern;
public class BigTrouser extends Finery {
@Override
public void show() {
System.out.print("垮裤 ");
this.component.show();
}
}
package DesignPattern.DecoratorPattern;
public class LeatherShoes extends Finery {
@Override
public void show() {
System.out.print("皮鞋 ");
this.component.show();
}
}
package DesignPattern.DecoratorPattern;
public class Sneaker extends Finery {
@Override
public void show() {
System.out.print("运动鞋 ");
this.component.show();
}
}
package DesignPattern.DecoratorPattern;
public class Suit extends Finery {
@Override
public void show() {
System.out.print("领带 ");
this.component.show();
}
}
package DesignPattern.DecoratorPattern;
public class Tshirts extends Finery {
@Override
public void show() {
System.out.print("大T恤 ");
this.component.show();
}
}
package DesignPattern.DecoratorPattern;
public class Client {
public static void main(String[] args){
Person xc=new Person("小明");
System.out.println("第一种装扮:");
Sneaker pqx=new Sneaker();
BigTrouser bt=new BigTrouser();
Tshirts ts=new Tshirts();
pqx.decorate(xc);
bt.decorate(pqx);
ts.decorate(bt);
ts.show();
System.out.println("\n第二种装扮");
LeatherShoes px=new LeatherShoes();
Tie ld=new Tie();
Suit su=new Suit();
px.decorate(xc);
ld.decorate(px);
su.decorate(ld);
su.show();
}
}