structure:装饰器模式 (Decorate Pattern) 2
- UID
- 1066743
|
structure:装饰器模式 (Decorate Pattern) 2
package Decorate;
public class Espresso extends Beverage {
//浓缩咖啡
public Espresso() {
description="Espresso";
}
@Override
public double cost() {
return 1.99;
}
}
package Decorate;
/*
具体组件,有点相当于半成品的意思
*/
public class HouseBlend extends Beverage {
public HouseBlend() {
description="House Blend Coffee";
}
@Override
public double cost() {
return 0.89;
}
}
package Decorate;
public class Mocha extends CondimentDecorator {
Beverage beverage;
public Mocha(Beverage beverage) {
this.beverage = beverage;
}
//描述完整的调用过程
@Override
public String getDescription() {
return beverage.getDescription()+", Mocha";
}
@Override
public double cost() {
return 0.20+beverage.cost();
}
}
package Decorate;
public class Soy extends CondimentDecorator {
Beverage beverage;
public Soy(Beverage beverage) {
this.beverage = beverage;
}
//描述完整的调用过程
@Override
public String getDescription() {
return beverage.getDescription()+", Soy";
}
@Override
public double cost() {
return 0.10+beverage.cost();
}
}
package Decorate;
public class TestDecorate {
public static void test(){
Beverage beverage=new Espresso();
System.out.println(beverage.getDescription()+" $"+beverage.cost());
Beverage beverage2=new DarkRoast();
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());
}
} |
|
|
|
|
|