Decorator Pattern 装饰者模式

来源:互联网 发布:openwrt网络尖兵 编辑:程序博客网 时间:2024/05/19 12:12

When I inherit behavior by subclassing, that behavior is set statically at compile time. In addition, all subclasses must inherit the same behavior. If however, I can extend an object's behavior through composition, then I can do this dynamically at runtime. It is possible for me to add multiple new responsibilities to objects through this technique, including responsibilities that were not even thought of by the designer of the superclass. And, I don't have to touch their code! By dynamically composing objects, I can add new functionality by writing new code rather than altering existing code. Bcause I'm not changing existing code, the chances of introducing bugs or causing unintended side effects in pre-existing code are much reduced.


Design Principle:

Classes should be open for extension, but closed for modification.

Classes are easy to extend to incorporate new behavior without modifying existing code.


Decorator Pattern: attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

装饰者模式在原有的Concrete Component基础上,利用Decorator包装上新的行为。


以饮料为例子:

Beverage是父抽象类(也可为接口),CondimentDecorator是继承Beverage的抽象类(也可为接口)。

public abstract class Beverage {String description = "Unknown Beverage";public String getDescription() {return description;}public abstract double cost();}

public abstract class CondimentDecorator extends Beverage{@Overridepublic abstract String getDescription();}

Concrete Beverage和Concrete Decorator:

public class Espresso extends Beverage{public Espresso() {description = "Espresso";}@Overridepublic double cost() {return 1.99;}}

public class Mocha extends CondimentDecorator{Beverage beverage;public Mocha(Beverage beverage) {this.beverage = beverage;}@Overridepublic String getDescription() {return beverage.getDescription() + ", Mocha";}@Overridepublic double cost() {return 1.20+beverage.cost();}}
Runtime Test:

public class TestMain {public static void main(String[] args) {Beverage beverage = new Espresso();beverage = new Mocha(beverage);System.out.println(beverage.getDescription() + ", cost " + beverage.cost());}}

装饰者模式:

Decorator和Component继承与同一个超类,类型一样。Decorator实际上是个Wrapper。以超类为引用,以Concrete Component为内核,用Decorator进行包装。Decorator内含有对于前一层Component的引用,所以能在其Component方法的基础上进行修改。Java 的IO就是这样chain起来的。

装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。

  1. 需要扩展一个类的功能,或给一个类增加附加责任。
  2. 需要动态地给一个对象增加功能,这些功能可以再动态地撤销。
  3. 需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不现实。

应用:咖啡添加调味剂,Java IO API.


0 0
原创粉丝点击