日期:2014-05-20 浏览次数:20884 次
//装饰者超类 public abstract class Beverage { private String description = "unknown description"; public String getDescription(){ return description; } public abstract double cost(); } public abstract class Decorator extends Beverage{ public abstract String getDescription(); } public class Coffee1 extends Beverage{ @Override public double cost() { return 2.0; //coffee1 价格2元 } @Override public String getDescription() { return "coffee1"; } } public class Coffee2 extends Beverage{ @Override public double cost() { return 4.0; //coffee2 价格4元 } @Override public String getDescription() { return "coffee2"; } } public class MilkDecorator extends Decorator { private Beverage mBeverage; public MilkDecorator(Beverage mBeverage) { super(); this.mBeverage = mBeverage; } @Override public String getDescription() { return mBeverage.getDescription() + " , milk"; } @Override public double cost() { return mBeverage.cost() + 1; //加牛奶一元 } } public class SugarDecorator extends Decorator { private Beverage mBeverage; public SugarDecorator(Beverage mBeverage) { super(); this.mBeverage = mBeverage; } @Override public String getDescription() { return mBeverage.getDescription() + " , sugar"; } @Override public double cost() { return mBeverage.cost() + 2; //加糖二元 } } public class Main { public static void main(String[] args) { System.out.println("要一份加糖的种类为coffee1的咖啡:"); Beverage beverage = new SugarDecorator(new Coffee1()); System.out.println("种类 : " + beverage.getDescription() + "\n价格 : " + beverage.cost()); System.out.println("要一份加糖加两份牛奶的种类为coffee2的咖啡:"); beverage = new SugarDecorator(new MilkDecorator(new MilkDecorator( new Coffee2()))); System.out.println("种类 : " + beverage.getDescription() + "\n价格 : " + beverage.cost()); } }