裝飾模式又稱封裝(Wrapper)模式,是以對用戶端透明的方式擴充項物件的功能,是繼承關係的一個替代方案。對用戶端透明意味著介面不變。
問題:
在OO設計和開發過程中, 經常會遇到下面的情況: 我們需要為已經設計好的類添加新的職責, 通常情況下我們會定義一個新類繼承自訂好的類. 由於組合比繼承更好(複雜度高,繼承深度深等原因, 見<設計模式解析>P39討論), 今天我們就來介紹一下應用的組合的裝飾模式.
類圖:
原始碼:
package com.designpatterns.decorator;
/**
* 抽象介面,規範準備接收附加責任的對象
* @author suki
*/
public interface Component {
void operation();
}
/**
* 接收附加責任, 此類型的類可以有多個, 只對應一個Decorator類
* @author suki
*/
public class ConcreteComponent implements Component{
public ConcreteComponent(){}
public void operation()
{
System.out.println("ConcreteComponent.operation()");
}
}
/**
* 裝飾角色,持有一個構件(Component)對象的執行個體,並定義一個與抽象構件介面一致的介面
* @author suki
*/
public class Decorator implements Component {
private Component component;
public Decorator(){}
public Decorator(Component component)
{
this.component = component;
}
public void operation() {
component.operation();
}
}
/**
* 添加附加責任
* @author suki
*/
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(){}
public ConcreteDecorator(Component component)
{
super(component);
}
public void operation()
{
super.operation();
this.addedOperation();
}
public void addedOperation()
{
System.out.println("ConcreteDecorator.addedOperation()");
}
}
/**
* 用戶端類
* @author suki
*/
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Decorator decorator = new ConcreteDecorator(component);
//用戶端不變, 但已增加了責任
decorator.operation();
}
}
總結:
在[GOF95]的書中:裝飾模式將更多的功能動態地附加到一個對象上。對功能擴充而言,裝飾模式提供了一個靈活的、可以替代繼承的選擇。
本書中451頁的發票系統的例子,好!