【风趣的解释】
Builder Mode
有时候带着MM去约会,KFC可能也是一个不错的约会地点,进去我们常常点上两个套餐,然后很happy的聊上一两个小时。有没有发现我们的选的套餐,都基本上是包括一个主食,几个辅食,一杯饮料呢?我们选好套餐,交了钱,收银员就把单子交给里面的师傅,然后师傅按照主食、辅食、饮料的顺序把食物放到盘子里(顺序可能有所不同,就暂且假设他们这样做吧),这其实就是一个建造者模式。
【正式的解释】
建造者模式
当面临“一个复杂对象”的创建工作,其通常由各个部分的子对象用一定的算法构成;由于需求的变化,这个复杂对象的各个部分经常面临着剧烈的变化,但是将它们组合在一起的算法确相对稳定。
【Python版】
#-*- coding:utf-8 -*-
#套餐A
class MealA(object):
def mainFood(self):
print "main food is ready."
def sideFood(self):
print "side food is ready."
def drink(self):
print "drink is ready."
#套餐B
class MealB(object):
def mainFood(self):
print "main food is ready."
def sideFood(self):
print "side food is ready."
def drink(self):
print "drink is ready."
#服务生
class Waiter(object):
def deliver(self, meal):
meal.mainFood()
meal.sideFood()
meal.drink()
if __name__ == "__main__":
waiter = Waiter()
waiter.deliver(MealA())
"""print out
main food is ready.
side food is ready.
drink is ready.
"""
【JS版】
//套餐A
function MealA(){
}
MealA.prototype = {
mainFood: function(){
console.log("main food is ready.");
},
sideFood: function(){
console.log("side food is ready.");
},
drink: function(){
console.log("drink food is ready.");
}
}
//套餐B
function MealB(){
}
MealB.prototype = {
mainFood: function(){
console.log("main food is ready.");
},
sideFood: function(){
console.log("side food is ready.");
},
drink: function(){
console.log("drink food is ready.");
}
}
//服务生
function Waiter(){
}
Waiter.prototype.deliver = function(meal){
meal.mainFood();
meal.sideFood();
meal.drink();
};
waiter = new Waiter();
waiter.deliver(new MealA());
/*console out
main food is ready.
side food is ready.
drink food is ready.
*/
网友评论