1、设计模式装饰者模式o 假设一个饮料店n 抽象一个饮料类o 但是,就某种饮料来说n 可以要求在其中加入各种调料n 例如:奶,巧克力,糖等n 加入不同的调料,会形成不同名称的饮料n 这样饮料的数量将会很多,即继承于饮料父类的子类将会很多n 每个子类的 cost()方法将计算出特定饮料加上调料的价钱o 这会造成维护的噩梦n 如果奶的价钱上涨n 如果新增一种调料o 现在要以饮料为主体o 运行时以调料来 “装饰 ”( decorate)饮料定义装饰者模式o public class DarkRoast extends Beverage o public DarkRoast() o description
2、 = “Dark Roast Coffee“;o o o public double cost() o return .99;o o o public class Mocha extends CondimentDecorator o Beverage beverage;o o public Mocha(Beverage beverage) o this.beverage = beverage;o o o public String getDescription() o return beverage.getDescription() + “, Mocha“;o o o public doubl
3、e cost() o return .20 + beverage.cost();o o o public class StarbuzzCoffee o o public static void main(String args) o Beverage beverage = new Espresso();o System.out.println(beverage.getDescription() o + “ $“ + beverage.cost();o o Beverage beverage2 = new DarkRoast();o beverage2 = new Mocha(beverage2
4、);o beverage2 = new Mocha(beverage2);o beverage2 = new Whip(beverage2);o System.out.println(beverage2.getDescription() o + “ $“ + beverage2.cost();o o Beverage beverage3 = new HouseBlend();o beverage3 = new Soy(beverage3);o beverage3 = new Mocha(beverage3);o beverage3 = new Whip(beverage3);o System.out.println(beverage3.getDescription() o + “ $“ + beverage3.cost();o o