装饰者(Component-Decorator)模式
动态的将责任附加到对象上,想要扩展功能,装饰者提供有别于继承的另外一种选择。
- 对扩展开放,对修改关闭
- 装饰者和被装饰者都有相同的超类型
- 装饰者可以在所委托被装饰者的行为之前或之后,加上自己的行为,以达到特定的目的。
- 对象可以在任何时候被装饰,所以可以在运行时动态地、不限量的用装饰者来装饰对象
个人总结
- 利用继承实现父类(被修饰者)的抽象方法。
- 子类方法需要定义构造器,传入父类被修饰者)对象
- 修饰:多次实例化,将上次的实例对象作为本次的实例化对象的traget传入。
具体实例
如手抓饼案例,根据加的菜不同,所得价格不同。
主题代码:
public abstract class Cake {
public abstract String getDescription();
public abstract double getcost();
}
观察者1:手抓饼
public class ShreddedCake extends Cake{
@Override
public double getcost() {
// TODO Auto-generated method stub
return 5.0;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return "Shredded Cake";
}
}
观察者2:加蛋
public class AddEggCake extends Cake{
public Cake cake;
public AddEggCake(Cake cake) {
// TODO Auto-generated constructor stub
this.cake = cake;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return "agg-"+cake.getDescription();
}
@Override
public double getcost() {
// TODO Auto-generated method stub
return cake.getcost()+3;
}
}
观察者3:加肉
public class AddMeatCake extends Cake{
private Cake cake;
public AddMeatCake(Cake cake ){
// TODO Auto-generated constructor stub
this.cake = cake;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return "meat-"+cake.getDescription();
}
@Override
public double getcost() {
// TODO Auto-generated method stub
return cake.getcost()+5;
}
}
Main测试:
public class MainTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Cake cake = new ShreddedCake();
System.out.print("This Cake is a "+cake.getDescription()+" , ");
System.out.println("and price is "+cake.getcost()+"元");
//将上面的cake实例对象作为AddEggCake的traget来创建AddEggCake对象。
cake = new AddEggCake(cake);
System.out.print("This Cake is a "+cake.getDescription()+" , ");
System.out.println("and price is "+cake.getcost()+"元");
cake = new AddMeatCake(cake);
System.out.print("This Cake is a "+cake.getDescription()+" , ");
System.out.println("and price is "+cake.getcost()+"元");
}
}
运行效果:
This Cake is a Shredded Cake , and price is 5.0元
This Cake is a agg-Shredded Cake , and price is 8.0元
This Cake is a meat-agg-Shredded Cake , and price is 13.0元