在不創建大量子類的前提下,動態地、透明地為對象添加額外職責。是繼承機制的靈活替代品。
| 角色 | 職責 | 代碼對應 |
|---|---|---|
| 抽象組件 | 定義核心接口,規範被裝飾對象契約 | Component 接口 |
| 具體組件 | 實現核心接口,基礎功能載體 | ConcreteComponent 類 |
| 抽象裝飾者 | 持有組件引用,實現組件接口,委託調用 | Decorator 抽象類 |
| 具體裝飾者 | 擴展具體功能,調用 super.operation() 形成鏈 | ConcreteDecorator1/2 類 |

public interface Component {
void doSomething();
}
public class ConcreteComponent implements Component {
@Override public void doSomething() { System.out.println("功能A"); }
}
public abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) { this.component = component; }
@Override public void doSomething() { component.doSomething(); }
}
public class ConcreteDecorator1 extends Decorator {
public ConcreteDecorator1(Component c) { super(c); }
@Override public void doSomething() {
super.doSomething(); // 執行被裝飾對象邏輯
doAnotherThing(); // 新增職責
}
private void doAnotherThing() { System.out.println("功能B"); }
}
public class ConcreteDecorator2 extends Decorator {
public ConcreteDecorator2(Component c) { super(c); }
@Override public void doSomething() {
super.doSomething();
doAnotherThing();
}
private void doAnotherThing() { System.out.println("功能C"); }
}
public class Test {
public static void main(String[] args) {
// 從內到外:Component → Decorator1 → Decorator2
Component component = new ConcreteDecorator2(
new ConcreteDecorator1(
new ConcreteComponent()));
component.doSomething();
}
}
輸出:
功能A 功能B 功能C
new BufferedReader(new InputStreamReader(new FileInputStream(...))))。典型應用:Java IO 流體系、Servlet Filter 鏈、Spring AOP 攔截器鏈、集合包裝 Collections.synchronizedList()。