【風趣的解釋】
Composite Mode
美眉最會用組合模式了逗堵。就拿陪妹妹逛商城來說叶眉,本來打算只給她買件衣服慷妙。進去店里僻焚,看見這個喜歡就拿上,看見那個喜歡就拿上膝擂,走這么一圈虑啤,衣服、包包架馋、鞋都整上了狞山。最后還給你撇一句,“喂叉寂,我買單你付錢萍启!”,真拿她們沒辦法办绝。一件也是付伊约,三件也是付,來世我也要做女人...
【正式的解釋】
組合模式
將對象組合成樹形結(jié)構(gòu)孕蝉,來表示部分與整體的關(guān)系屡律。它使單個對象和組合對象的使用具有一致性。
【Python版】
#-*- coding:utf-8 -*-
#物品
class Stuff(object):
def __init__(self, name, price):
self.name = name
self.price = price
def des(self):
print self.name + " : " + str(self.price)
#購物單
class Order(object):
def __init__(self):
self.orderComponentList = []
def add(self, orderComponent):
self.orderComponentList.append(orderComponent)
def des(self):
for stuff in self.orderComponentList:
stuff.des()
if __name__ == "__main__":
#美眉的購物單
girlOrder = Order()
girlOrder.add(Stuff("shoe", 120))
girlOrder.add(Stuff("handbag", 220))
girlOrder.add(Stuff("dress", 320))
#我的的購物單
boyOrder = Order()
boyOrder.add(Stuff("T shirt", 230))
#我倆的購物單降淮,總之都是我付錢
bothOrder = Order()
bothOrder.add(girlOrder)
bothOrder.add(boyOrder)
bothOrder.des()
"""print out
shoe : 120
handbag : 220
dress : 320
T shirt : 230
"""
【JS版】
//物品
function Stuff(name, price){
this.name = name;
this.price = price;
}
Stuff.prototype.des = function(){
console.log(this.name + ' : ' + this.price);
};
//購物單
function Order(){
this.orderComponentList = []
}
Order.prototype.add = function(obj){
this.orderComponentList.push(obj);
};
Order.prototype.des = function(){
for(var i in this.orderComponentList){
this.orderComponentList[i].des();
}
};
var girlOrder = new Order(),
boyOrder = new Order(),
bothOrder = new Order();
//美眉的購物單
girlOrder.add(new Stuff("shoe", 120));
girlOrder.add(new Stuff("handbag", 220));
girlOrder.add(new Stuff("dress", 320));
//我的的購物單
boyOrder.add(new Stuff("T shirt", 230));
//我倆的購物單超埋,總之都是我付錢
bothOrder.add(girlOrder);
bothOrder.add(boyOrder);
bothOrder.des();
/*console out
shoe : 120
handbag : 220
dress : 320
T shirt : 230
*/