在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。标签:cost,getDescription,模式,public,案例,Beverage,return,装饰,beverage From: https://blog.51cto.com/u_12026373/5930797
拿一个咖啡对象,以摩卡对象来装饰它,以奶泡对象来装饰它,调用cost方法,并依靠委托将调料的价格加进去
public abstract class Beverage {
//原味类
//默认包访问权限
String description="Unknown Beverage";
public String getDescription(){
return description;
}
public abstract double cost();
}
//调料基础类
public abstract class CondimentDecorator extends Beverage{
public abstract String getDescription();
}
//一种饮料
public class Espresso extends Beverage{
public Espresso(){
description="Espresso";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 1.99;
}
}
//一种饮料
public class HouseBlend extends Beverage{
public HouseBlend(){
description="House Blend Coffee";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 0.89;
}
}
//一种调料
public class Mocha extends CondimentDecorator{
Beverage beverage;
public Mocha(Beverage beverage){
this.beverage=beverage;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return beverage.getDescription()+",Mocha";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 0.20+beverage.cost();
}
}
public class Soy extends CondimentDecorator{
Beverage beverage;
public Soy(Beverage beverage){
this.beverage=beverage;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return beverage.getDescription()+",Soy";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 0.20+beverage.cost();
}
}
public class Whip extends CondimentDecorator{
Beverage beverage;
public Whip(Beverage beverage){
this.beverage=beverage;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return beverage.getDescription()+",Whip";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 0.20+beverage.cost();
}
}
测试:public class MyTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Beverage beverage=new Espresso();//订了一杯Espresso,不需要调料,打印出它的描述与价格
System.out.println(beverage.getDescription()+" $"+beverage.cost());
Beverage beverage2=new Espresso();
beverage2=new Mocha(beverage2);
beverage2=new Mocha(beverage2);
beverage2=new Whip(beverage2);
System.out.println(beverage2.getDescription()+" $"+beverage2.cost());
Beverage beverage3=new HouseBlend();
beverage3=new Soy(beverage3);
beverage3=new Mocha(beverage3);
beverage3=new Whip(beverage3);
System.out.println(beverage3.getDescription()+" $"+beverage3.cost());
}
}效果:
Espresso $1.99
Espresso,Mocha,Mocha,Whip $2.5900000000000003
House Blend Coffee,Soy,Mocha,Whip $1.49