java设计模式--装饰者模式

照例搬一篇文章连接,我一般会选择带有uml图的 方便理解,我只贴代码,因为我觉得别人理解的比我透彻,写的比我好 http://www.cnblogs.com/stonefeng/p/5679638.html

装饰者模式可以给对象添加一些额外的东西,设计模式那种书中举例是星巴克的例子,如果每一种做法都写一个类的话大概会爆炸,所以选择灵活的方式

1.创建抽象类,定义基本的行为,装饰者和被装饰着都去继承他

public abstract class Component {

public String desc = "我是抽象组件,他们的共同父类";

public String getDesc() {
return desc;
}

public abstract int price();

}

2.被装饰者

public class ACupCoffe extends Component{

public ACupCoffe() {
desc = "一杯咖啡";
}
@Override
public int price() {
// TODO Auto-generated method stub
return 10;
}

}

3.装饰者

public abstract class Decorator extends Component{

public abstract String getDesc();
}

4.具体装饰者1

public class Coffee extends Decorator{

private Component acupcoffe;

public Coffee(Component acupcoffe) {
this.acupcoffe = acupcoffe;
}
@Override
public String getDesc() {
// TODO Auto-generated method stub
return acupcoffe.getDesc() + "咖啡";
}

@Override
public int price() {
// TODO Auto-generated method stub
return acupcoffe.price() + 10;
}

}

5.具体装饰者2

public class Sugar extends Decorator{

private Component acupcoffe;
public Sugar(Component aCupCoffe) {
this.acupcoffe = aCupCoffe;
}
@Override
public String getDesc() {

return acupcoffe.getDesc() + "糖";
}

@Override
public int price() {
// TODO Auto-generated method stub
return acupcoffe.price() + 10;
}

}

6.客户端

public class Client {

public static void main(String[] args) {
Component aCupCoffe = new ACupCoffe();

aCupCoffe = new Sugar(aCupCoffe);
System.out.println(aCupCoffe.getDesc());
System.out.println(aCupCoffe.price());

aCupCoffe = new Coffee(aCupCoffe);
System.out.println(aCupCoffe.getDesc());
System.out.println(aCupCoffe.price());
}

}

原文地址:https://www.cnblogs.com/leavesss/p/9969611.html