我正在運行Addy Osmani關於裝飾模式的教程(在這裏找到http://addyosmani.com/blog/decorator-pattern/),我對如何在Javascript中實現最簡單的裝飾器有點困惑。看起來有些示例使用obj.prototype模式爲現有對象添加功能,有些示例創建獨立功能並傳遞對象。Javascript裝飾模式 - 原型還是單一功能?
// Decorator Pattern ?
function coffee(size, flavors) {
this._size = size || "medium";
this._flavors = flavors || [];
this._cost = 100;
this.info = function() {
console.log(this._size, this._flavors, this._cost);
}
}
// Decorator - Would this be considered a decorator since the functionality needed to add flavors default to the coffee object?
function addFlavor(coffee, flavor) {
coffee._flavors.push(flavor);
coffee._cost = coffee._cost + 25;
}
// Decorator - Engrave the cup? lol
function engraving(coffee) {
coffee._cost = coffee._cost + 200;
}
// Decorator Variation w/ prototype instead - Add cream
coffee.prototype.addCream = function() {
this._cost = this._cost + 100;
};
// Instantiate Coffee
testCoffee = new coffee('Large', ['vanilla']);
// Add Flavors
addFlavor(testCoffee, 'chocolate');
addFlavor(testCoffee, 'almond');
addFlavor(testCoffee, 'hazelnut');
// Add Engraving
engraving(testCoffee);
// Add Cream
testCoffee.addCream();
// Log it all to the console
testCoffee.info();
一本例中的jsfiddle可以在這裏找到:http://jsfiddle.net/pathsofdesign/ocbbzoy2/
我的問題(S):它看起來像我可以實現使用原型繼承Decorator模式。有沒有這樣做的優點或缺點(即:我的addCream()方法)? 謝謝!
UPDATE:
它看起來像我的例子不是實際執行Decorator模式可言。 @Etai和@Bergi都在下面給出了很好的答案。如果我理解正確,傳統的JS裝飾器會'包裝'另一個obj,然後調整該特定對象的行爲而不修改基礎對象。
你究竟在問什麼* * – 2014-09-29 19:13:12
@AlexWayne - 我更新了我的問題,抱歉我不清楚。 – Pathsofdesign 2014-09-29 19:22:34