装饰者模式

【风趣的解释】

Decorator Mode

家里又让我相亲,说是这个美眉是我的菜,人长得漂亮,心地又好。嘿嘿,那就准备下呗!换个新发型、新衣服、新鞋子,好好的装饰一下自己。

【正式的解释】

建造者模式

装饰者提供比继承更有弹性、更灵活的替代方案。可以动态给一个对象添加新的功能,也可以动态的取消。

【Python版】

#-*- coding:utf-8 -*-

#装饰者
class Decorator(object):
    def __init__(self, *args):
        if args:
            self.obj = args[0]
        else:
            self.obj = None

    def getPrice(self):
        if self.obj:
            return self.obj.getPrice() + ', ' + self.name + ': ' + str(self.price)
        else:
            return self.name + ': ' + str(self.price)

    def getCost(self):
        if self.obj:
            return float(self.obj.getCost()) + float(self.price)
        else:
            return float(self.price)
#新发型
class NewHair(Decorator):
    def __init__(self, *args):
        self.name = "new hair style"
        self.price = "20"
        super(self.__class__, self).__init__(*args)
#新衣服
class NewCloth(Decorator):
    def __init__(self, *args):
        self.name = "new cloth"
        self.price = "200"
        super(self.__class__, self).__init__(*args)
#新鞋子
class NewShoes(Decorator):
    def __init__(self, *args):
        self.name = "new shoes"
        self.price = "130"
        super(self.__class__, self).__init__(*args)

if __name__ == "__main__":
    #我的所有装备
    equipment = NewHair()
    equipment = NewCloth(equipment)
    equipment = NewShoes(equipment)

    print equipment.getPrice()
    print "total cost: ", equipment.getCost()

"""print out

new hair style: 20, new cloth: 200, new shoes: 130
total cost:  350.0
"""

【JS版】

//装饰者
function Decorator(){

}
Decorator.prototype.getPrice = function(){
    if(typeof this.obj !== 'undefined'){
        return this.obj.getPrice() + ', ' + this.name + ': ' + this.price;
    }else{
        return this.name + ': ' + this.price;
    }
};
Decorator.prototype.getCost = function(){
    if(typeof this.obj !== 'undefined'){
        return parseFloat(this.obj.getCost()) + parseFloat(this.price);
    }else{
        return parseFloat(this.price);
    }
};

//新发型
function NewHair(obj){
    this.name = "new hair style";
    this.price = "20";
    this.obj = obj;
}
NewHair.prototype = Decorator.prototype;

//新衣服
function NewCloth(obj){
    this.name = "new cloth";
    this.price = "200";
    this.obj = obj;
}
NewCloth.prototype = Decorator.prototype;

//新鞋子
function NewShoes(obj){
    this.name = "new shoes";
    this.price = "130";
    this.obj = obj;
}
NewShoes.prototype = Decorator.prototype;

//我的所有装备
var equipment = new NewHair();
equipment = new NewCloth(equipment);
equipment = new NewShoes(equipment);

console.log(equipment.getPrice());
console.log('total cost:' + equipment.getCost());

/*console out

new hair style: 20, new cloth: 200, new shoes: 130
total:350
*/

你可能感兴趣的:(装饰者模式)