Java装饰者模式

时间:2024-10-09 13:36:45

定义:在不改变原有对象的基础上,将功能附加到对象自上

提供了比继承更有弹性的替代方案(扩展原有对象功能)

类型:结构型

扩展一个类的功能或给一个类添加附加职责

动态的给一个对象添加功能,这些功能可以再动态的撤销

继承的有力补充,比继承灵活,不改变原有对象的情况下给一个对象扩展功能

通过使用不同装饰类以及这些装饰类的排列组合,可以实现不同效果

缺点:

会出现更多的代码,更多的类,增加程序复杂性

动态装饰时,多层装饰时会更加复杂

public abstract class ABattercake {
protected abstract String getDesc();;
protected abstract int cost();
}
public class Battercake extends ABattercake {
@Override
protected String getDesc() {
return "jianbing";
} @Override
protected int cost() {
return 8;
}
}
public class AbstractDecorator extends ABattercake {
private ABattercake aBattercake;
public AbstractDecorator (ABattercake aBattercake){
this.aBattercake=aBattercake;
}
@Override
protected String getDesc() {
return this.aBattercake.getDesc();
} @Override
protected int cost() {
return this.aBattercake.cost();
}
} 
public class EggDecorator extends  AbstractDecorator {
public EggDecorator(ABattercake aBattercake){
super(aBattercake);
}
@Override
protected String getDesc() {
return super.getDesc()+" jiayigejidan";
} @Override
protected int cost() {
return super.cost()+1;
}
}

 

public class SausageDecorator extends AbstractDecorator{

    public SausageDecorator(ABattercake aBattercake){
super(aBattercake);
} @Override
protected String getDesc() {
return super.getDesc()+" jiayigenxiangchang";
} @Override
protected int cost() {
return super.cost()+2;
}
}
public class Test {
public static void main(String[] args) {
ABattercake aBattercake;
aBattercake=new Battercake();
aBattercake=new EggDecorator(aBattercake);
aBattercake=new EggDecorator(aBattercake);
aBattercake=new SausageDecorator(aBattercake); System.out.println(aBattercake.getDesc()+""+aBattercake.cost());
}
}

  类图:

Java装饰者模式