我正在研究GOF中記錄的Decorator模式。請幫助我了解裝飾器模式。有人可以舉一個在現(xiàn)實世界中有用的用例示例嗎?
4 回答

皈依舞
TA貢獻1851條經(jīng)驗 獲得超3個贊
這是一個簡單的示例,將新行為動態(tài)添加到現(xiàn)有對象或Decorator模式中。由于動態(tài)語言(例如Javascript)的性質,這種模式成為語言本身的一部分。
// Person object that we will be decorating with logging capability
var person = {
name: "Foo",
city: "Bar"
};
// Function that serves as a decorator and dynamically adds the log method to a given object
function MakeLoggable(object) {
object.log = function(property) {
console.log(this[property]);
}
}
// Person is given the dynamic responsibility here
MakeLoggable(person);
// Using the newly added functionality
person.log('name');
- 4 回答
- 0 關注
- 635 瀏覽
添加回答
舉報
0/150
提交
取消