Decorator模式设计模式
装饰者模式定义:动态地将责任附加到对象上。
若要扩展功能。装饰者提供了比继续更有弹性的替代方案。
简单定义:包装一个对象。以提供新的行为。
装饰者模式能够有效应对类爆炸问题。
OO原则:
对扩展开放,对改动关闭。
以书中的StarbuzzCoffee为例:
Beverage.java(饮料抽象类)
package headfirst.decorator.starbuzz; public abstract class Beverage { String description = "Unknown Beverage"; public String getDescription() { return description; } public abstract double cost(); }
CondimentDecorator.java(调料抽象类)
package headfirst.decorator.starbuzz; public abstract class CondimentDecorator extends Beverage { public abstract String getDescription(); }
DarkRoast.java(饮料详细类)
package headfirst.decorator.starbuzz; public class DarkRoast extends Beverage { public DarkRoast() { description = "Dark Roast Coffee"; } public double cost() { return .99; } }
Espresso.java
package headfirst.decorator.starbuzz; public class Espresso extends Beverage { public Espresso() { description = "Espresso"; } public double cost() { return 1.99; } }
HouseBlend.java
package headfirst.decorator.starbuzz; public class HouseBlend extends Beverage { public HouseBlend() { description = "House Blend Coffee"; } public double cost() { return .89; } }
Mocha.java(调料详细类)
package headfirst.decorator.starbuzz; public class Mocha extends CondimentDecorator { Beverage beverage; public Mocha(Beverage beverage) { this.beverage = beverage; } public String getDescription() { return beverage.getDescription() + ", Mocha"; } public double cost() { return .20 + beverage.cost(); } }
Soy.java
package headfirst.decorator.starbuzz; public class Soy extends CondimentDecorator { Beverage beverage; public Soy(Beverage beverage) { this.beverage = beverage; } public String getDescription() { return beverage.getDescription() + ", Soy"; } public double cost() { return .15 + beverage.cost(); } }
Whip.java
package headfirst.decorator.starbuzz; public class Whip extends CondimentDecorator { Beverage beverage; public Whip(Beverage beverage) { this.beverage = beverage; } public String getDescription() { return beverage.getDescription() + ", Whip"; } public double cost() { return .10 + beverage.cost(); } }
測试类:StarbuzzCoffee.java
package headfirst.decorator.starbuzz; public class StarbuzzCoffee { public static void main(String args[]) { Beverage beverage = new Espresso(); System.out.println(beverage.getDescription() + " $" + beverage.cost()); Beverage beverage2 = new DarkRoast(); beverage2 = new Mocha(beverage2); beverage2 = new Mocha(beverage2); beverage2 = new Whip(beverage2); System.out.println(beverage2.getDescription() + " $" + beverage2.cost()); Beverage beverage3 = new HouseBlend(); beverage3 = new Soy(beverage3); beverage3 = new Mocha(beverage3); beverage3 = new Whip(beverage3); System.out.println(beverage3.getDescription() + " $" + beverage3.cost()); } }
输出:
Espresso $1.99 Dark Roast Coffee, Mocha, Mocha, Whip $1.49 House Blend Coffee, Soy, Mocha, Whip $1.34
版权声明:本文博客原创文章,博客,未经同意,不得转载。