所有饮料抽象类
装饰者抽象类
浓咖啡
佐料(装饰者)摩卡类
设计原则
对扩展开放,对修改关闭
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 Mocha extends CondimentDecorator {
Beverage beverage;
public Mocha(Beverage beverage){
this.beverage = beverage;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
System.out.println(beverage.getDescription());
return beverage.getDescription()+",Mocha";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return .20 +beverage.cost();
}
}
public class StarbuzzCoffee {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//单纯的咖啡
Beverage beverage = new Espresso();
//加入摩卡的咖啡
beverage = new Mocha(beverage);
System.out.println(beverage.getDescription()+" $ "+beverage.cost());
}
}
设计原则
对扩展开放,对修改关闭