【風(fēng)趣的解釋】
Decorator Mode
家里又讓我相親帕膜,說是這個(gè)美眉是我的菜粱甫,人長得漂亮,心地又好茶宵。嘿嘿危纫,那就準(zhǔn)備下唄乌庶!換個(gè)新發(fā)型、新衣服瞒大、新鞋子,好好的裝飾一下自己透敌。
【正式的解釋】
建造者模式
裝飾者提供比繼承更有彈性、更靈活的替代方案酗电。可以動(dòng)態(tài)給一個(gè)對(duì)象添加新的功能撵术,也可以動(dòng)態(tài)的取消。
【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)
#新發(fā)型
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);
}
};
//新發(fā)型
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
*/