標籤:javascript
介紹
裝飾者提供比繼承更有彈性的替代方案。 裝飾者用用於封裝同介面的對象,不僅允許你向方法添加行為,而且還可以將方法設定成原始對象調用(例如裝飾者的建構函式)。
裝飾者用於通過重載方法的形式添加新功能,該模式可以在被裝飾者前面或者後面加上自己的行為以達到特定的目的。
本文
那麼裝飾者模式有什麼好處呢?前面說了,裝飾者是一種實現繼承的替代方案。當指令碼運行時,在子類中增加行為會影響原有類所有的執行個體,而裝飾者卻不然。取而代之的是它能給不同對象各自添加新行為。如下代碼所示:
//需要裝飾的類(函數)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時,它不僅具有一些裝飾者的行為,同時也調用了下層對象的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(); // 第7步:先執行原型(這時候是Angel了)的decorate方法 console.log(‘Put on some red balls‘); // 第8步 再輸出 red // 將這2步作為RedBalls的decorate方法 }};tree.BlueBalls = function () { this.decorate = function () { this.BlueBalls.prototype.decorate(); // 第1步:先執行原型的decorate方法,也就是tree.decorate() console.log(‘Add blue balls‘); // 第2步 再輸出blue // 將這2步作為BlueBalls的decorate方法 }};tree.Angel = function () { this.decorate = function () { this.Angel.prototype.decorate(); // 第4步:先執行原型(這時候是BlueBalls了)的decorate方法 console.log(‘An angel on the top‘); // 第5步 再輸出angel // 將這2步作為Angel的decorate方法 }};tree = tree.getDecorator(‘BlueBalls‘); // 第3步:將BlueBalls對象賦給tree,這時候父原型裡的getDecorator依然可用tree = tree.getDecorator(‘Angel‘); // 第6步:將Angel對象賦給tree,這時候父原型的父原型裡的getDecorator依然可用tree = tree.getDecorator(‘RedBalls‘); // 第9步:將RedBalls對象賦給treetree.decorate(); // 第10步:執行RedBalls對象的decorate方法總結
裝飾者模式是為已有功能動態地添加更多功能的一種方式,把每個要裝飾的功能放在單獨的函數裡,然後用該函數封裝所要裝飾的已有函數對象,因此,當需要執行特殊行為的時候,調用代碼就可以根據需要有選擇地、按順序地使用裝飾功能來封裝對象。優點是把類(函數)的核心職責和裝飾功能區分開了。
著作權聲明:本文為博主http://www.zuiniusn.com 原創文章,未經博主允許不得轉載。
深入理解JavaScript系列(29):設計模式之裝飾者模式