装饰模式:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
例子:你要替一家咖啡店设计beverage类。beverage有很多种,并且可以添加许多的调料,比如蒸奶、豆浆、摩卡等。
1 public abstract class Beverage 2 { 3 String description = "Unknown Beverage"; 4 5 public String getDescription() 6 { 7 return description; 8 } 9 10 public abstract double cost(); 11 } 12 13 public class Espresso extends Beverage 14 { 15 public Espresso() 16 { 17 description = "Espresso"; 18 } 19 20 @Override 21 public double cost() 22 { 23 return 1.99; 24 } 25 } 26 27 public abstract class CondimentDecorator extends Beverage 28 { 29 public abstract String getDescription(); 30 } 31 32 public class Mocha extends CondimentDecorator 33 { 34 Beverage beverage; 35 36 Mocha(Beverage beverage) 37 { 38 this.beverage = beverage; 39 } 40 41 @Override 42 public String getDescription() 43 { 44 return beverage.getDescription() + ", Mocha"; 45 } 46 47 @Override 48 public double cost() 49 { 50 return .20 + beverage.cost(); 51 } 52 } 53 54 public class Whip extends CondimentDecorator 55 { 56 Beverage beverage; 57 58 Whip(Beverage beverage) 59 { 60 this.beverage = beverage; 61 } 62 63 @Override 64 public String getDescription() 65 { 66 return beverage.getDescription() + ", Whip"; 67 } 68 69 @Override 70 public double cost() 71 { 72 return .35 + beverage.cost(); 73 } 74 } 75 76 public class test 77 { 78 public static void main(String[] args) 79 { 80 Beverage espresso = new Espresso(); 81 Beverage espresso_mocha = new Mocha(espresso); 82 Beverage espresso_mocha_whip = new Whip(espresso_mocha); 83 output(espresso_mocha_whip); 84 } 85 86 public static void output(Beverage beverage) 87 { 88 System.out.println(beverage.getDescription() + " $: " + beverage.cost()); 89 } 90 }
注:JAVA I/O中利用了装饰模式。