设计模式-装饰者模式
-
定义
装饰者模式动态地将责任责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。 -
实现要点
装饰器与被装饰的类需要继承自相同接口,来达到类型匹配。装饰器持有被装饰的类的实例。 -
代码实例
/** * 基础组件 */ abstract class Beverage { private String description = "Unknown Beverage"; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public abstract double cost(); } /** * 装饰器基类 */ abstract class Decorator extends Beverage { @Override public abstract String getDescription(); } /** * 被装饰的类 */ class Espresso extends Beverage { public Espresso() { setDescription("Espresso"); } @Override public double cost() { return 1.99; } } /** * 装饰器 */ class Mocha extends Decorator { private Beverage beverage; public Mocha(Beverage beverage) { this.beverage = beverage; } @Override public double cost() { return beverage.cost() + 0.29; } @Override public String getDescription() { return beverage.getDescription() + ", Mocha"; } } class CoffeeTest { public static void main(String[] args) { Beverage beverage = new Espresso(); beverage = new Mocha(beverage); System.out.println(beverage.getDescription() + " " + beverage.cost()); } }