DIV CSS 佈局教程網

設計模式入門:靈活的裝飾者模式
編輯:JavaScript綜合知識     

裝飾者模式(Decorator)是繼承之外的一種替代方案,它能在不改動原物件的前提下,動態地為物件添加新職責。相比繼承,它更加靈活,也更符合「對修改關閉、對擴展開放」的設計原則。

為什麼需要裝飾者

裝飾者用於包裝相同介面的物件,不僅能為方法添加行為,還能保留對原始物件的呼叫。它的核心在於:當程式運行時,在子類中增加行為會影響該類的所有實例,而裝飾者卻能為「不同物件」各自添加不同的行為。

範例一:電腦加購配件

用一個買電腦的例子來說明。基本款 Macbook 有基礎價格,而記憶體、光驅、保險等都是可以逐層加購的裝飾:

代碼如下:
//需要裝飾的類(函數)
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());

這種「洋蔥式」的嵌套,正是裝飾者模式的精髓。

範例二:任務前後擴充

下面這個例子展示了如何在呼叫 performTask 時,同時觸發裝飾者的行為與下層物件的行為:

代碼如下:
function ConcreteClass() {
this.performTask = function () {
this.preTask();
console.log('doing something');
this.postTask();
};
}
function AbstractDecorator(decorated) {
this.performTask = function () {
decorated.performTask();
};
}
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 decorator1 = new ConcreteDecoratorClass(concrete);
var decorator2 = new ConcreteDecoratorClass(decorator1);
decorator2.performTask();

範例三:聖誕樹裝飾

最後是一個很形象的例子——幫聖誕樹掛上不同裝飾:

代碼如下:
var tree = {};
tree.decorate = function () {
console.log('Make sure the tree won\'t fall');
};
tree.getDecorator = function (deco) {
tree[deco].prototype = this;
return new tree[deco];
};
tree.RedBalls = function () {
this.decorate = function () {
this.RedBalls.prototype.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 = tree.getDecorator('BlueBalls');
tree = tree.getDecorator('Angel');
tree = tree.getDecorator('RedBalls');
tree.decorate();

總結

裝飾者模式為既有功能動態添加新能力的一種方式。它把每個裝飾功能放進獨立的函式,再以此包裝要裝飾的物件,因此呼叫時就能按需、按序地套用裝飾。它最大的優點,是把類(函式)的核心職責與裝飾功能清楚地分開了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved