裝飾者提供比繼承更彈性的替代方案:包裝相同介面的物件,不僅能為方法新增行為,還能將呼叫委託給原始物件。運行時動態組合,避免子類爆炸,單一職責原則極佳體現。
// 基礎物件
function Macbook() {
this.cost = function() { return 1000; };
}
// 裝飾者:記憶體升級
function Memory(macbook) {
this.cost = function() { return macbook.cost() + 75; };
}
// 裝飾者:藍光光碟機
function BlurayDrive(macbook) {
this.cost = function() { return macbook.cost() + 300; };
}
// 裝飾者:保險
function Insurance(macbook) {
this.cost = function() { return macbook.cost() + 250; };
}
// 使用:層層包裝
var myMacbook = new Insurance(new BlurayDrive(new Memory(new Macbook())));
console.log(myMacbook.cost()); // 1000+75+300+250 = 1625
每個裝飾者持有被裝飾者引用,cost() 呼叫鏈向內傳遞,最後由核心物件回傳基礎價格,再層層累加。
// 核心任務
function ConcreteClass() {
this.performTask = function() {
this.preTask();
console.log('doing something');
this.postTask();
};
}
// 抽象裝飾者:透傳 performTask
function AbstractDecorator(decorated) {
this.performTask = function() { decorated.performTask(); };
}
// 具體裝飾者:新增 pre/post 行為
function ConcreteDecoratorClass(decorated) {
this.base = AbstractDecorator;
this.base(decorated); // 繼承透傳邏輯
decorated.preTask = function() { console.log('pre-calling..'); };
decorated.postTask = function() { console.log('post-calling..'); };
}
// 疊加裝飾
var concrete = new ConcreteClass();
var d1 = new ConcreteDecoratorClass(concrete);
var d2 = new ConcreteDecoratorClass(d1);
d2.performTask();
// 輸出:
// pre-calling..
// pre-calling..
// doing something
// post-calling..
// post-calling..
var tree = {};
tree.decorate = function() { console.log("Make sure the tree won't fall"); };
tree.getDecorator = function(deco) {
tree[deco].prototype = this; // 將當前 tree 設為裝飾者的原型
return new tree[deco];
};
tree.RedBalls = function() {
this.decorate = function() {
this.RedBalls.prototype.decorate(); // 呼叫原型 (上一層) decorate
console.log("Put on some red balls");
};
};
tree.BlueBalls = function() {
this.decorate = function() {
this.BlueBalls.prototype.decorate();
console.log("Add blue balls");
};
};
tree.Angel = function() {
this.decorate = function() {
this.Angel.prototype.decorate();
console.log("An angel on the top");
};
};
// 建構裝飾鏈:tree → BlueBalls → Angel → RedBalls
tree = tree.getDecorator('BlueBalls');
tree = tree.getDecorator('Angel');
tree = tree.getDecorator('RedBalls');
tree.decorate();
// 輸出順序:
// Make sure the tree won't fall
// Add blue balls
// An angel on the top
// Put on some red balls
| 實作風格 | 特點 | 適用場景 |
|---|---|---|
| 組合+委託 (範例一) | 構造函數接收被裝飾者,方法內呼叫 wrapped.method() | 單一方法擴充、價格計算、屬性疊加 |
| 繼承透傳 (範例二) | 抽象裝飾者繼承核心介面,具體裝飾者修改被裝飾者原型 | 需在方法前後統一攔截(日誌、計時、權限) |
| 原型鏈鏈式 (範例三) | 每層將自己設為下一層原型,prototype.method() 呼叫上一層 | 動態增減裝飾層、順序敏感的管線處理 |
instanceof 可能失效(被包裹後型別改變)。裝飾者模式是「動態擴充行為」的利器。JavaScript 的動態特性(物件可隨時增減屬性、函式為一等公民)使其實作極為自然。實務中常見於:Middleware 鏈、日誌攔截、權限驗證、資料轉換管線等場景。