javascript设计模式之装饰者模式

/*
 * 装饰者模式提供比继承更有弹性的替代方案
 * 在不改变原构造函数的情况下,添加新的属性或功能
*/

//需要装饰的类(函数)
function Macbook() {
    this.cost = function () {
        return 1000;
    };
}

// 加个内存
function Memory(macbook) {
    this.cost = function () {
        return macbook.cost() + 100;
    };
}

// 再买个保险
function Insurance(macbook) {
    this.cost = function () {
        return macbook.cost() + 250;
    };
}


var myMac = new Insurance(new Memory(new Macbook()));

console.log(myMac.cost());  // 1350

 

posted @ 2014-09-11 16:22  farawayfromhome  阅读(269)  评论(0编辑  收藏  举报