装饰模式最大的好处就是避免在添加类的职责时使用单纯的继承,本来想写个例子体会继承的痛苦,改进了下,写成了组合的形式:
public class Person {
private String name;
private Set<Clothes> clothes = new HashSet<Clothes>();
public void show(){
for(Clothes c :clothes){
c.show();
}
System.out.println(this.name+" wear");
}
public void setName(String name) {
this.name = name;
}
public void add(Clothes cloth){
this.clothes.add(cloth);
}
}
public abstract class Clothes{
public void show(){
}
}
public class BigTrousers extends Clothes {
@Override
public void show() {
System.out.println("Big Trousers");
}
}
public class TShirt extends Clothes{
@Override
public void show() {
System.out.println("T-shirt");
}
}
很明显,Person中聚合了一堆它要穿的东西,需要的时候显示出来:
public static void main(String[] args) {
Person p = new Person();
p.setName("XIao");
TShirt t = new TShirt();
BigTrousers bt = new BigTrousers();
p.add(t);
p.add(bt);
p.show();
}
这样同样能做到动态添加职责的效果,相对于装饰的劣势是无法确定调用的顺序。
看看类图:
这不是策略模式吗? 哇哈哈哈哈~