【風(fēng)趣的解釋】
Factory Method Mode
追美眉少不了請吃飯溯泣,麥當勞的雞翅和KFC的雞翅都是美眉喜歡吃的鹏往。雖然口味有所不同蓖租,但不管帶美眉去麥當勞還是KFC纪挎,只要向服務(wù)生說“來四個雞翅”就行了颤介。簡單的說梳星,麥當勞和KFC就是生產(chǎn)雞翅的Factory。
【正式的解釋】
工廠方法模式
消費者類和工廠類分開滚朵。消費者任何時候需要某種產(chǎn)品冤灾,只需向工廠請求即可。優(yōu)點: 消費者無須修改就可以接納新產(chǎn)品辕近。缺點: 當產(chǎn)品需要修改時韵吨,工廠類也需要做修改(如何生成產(chǎn)品、向消費者提供)移宅。
【Python版】
#-*-coding:utf-8 -*-
#KFC store
class KFCStore():
def getChikenWing(self):
return "DFC chicken wing."
#MCD store
class MCDStore():
def getChikenWing(self):
return "MCD chicken wing."
#ChickenWing Factory
class ChickenWingFactory(object):
def createChickenWing(self, obj):
return obj.getChikenWing()
if __name__ == "__main__":
chickenWingFactory = ChickenWingFactory()
print chickenWingFactory.createChickenWing(KFCStore())
print chickenWingFactory.createChickenWing(MCDStore())
"""print out
DFC chicken wing.
MCD chicken wing.
"""
【JS版】
//KFC store
function KFCStore(){
}
KFCStore.prototype.getChickenWing = function(){
return "KFC chicken wing.";
};
//MCD store
function MCDStore(){
}
MCDStore.prototype.getChickenWing = function(){
return "MCD chicken wing.";
};
//ChickenWing Factory
function ChickenWingFactory(){
}
ChickenWingFactory.prototype.createChickenWing = function(obj){
return obj.getChickenWing()
};
var chickenWingFactory = new ChickenWingFactory();
console.log(chickenWingFactory.createChickenWing(new KFCStore()));
console.log(chickenWingFactory.createChickenWing(new MCDStore()));
/*console out
KFC chicken wing.
MCD chicken wing.
*/