Java装饰模式
最近我想看下Java里的装饰模式 在网上找了一下 都是一大篇的代码 看着头疼 希望各位能给我写一个简单的列子 要是可以的话加上注释就更好了 麻烦了各位 谢谢
[解决办法]
//装饰者超类 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()); } }