抽象工厂模式
2013-08-12 本文已影响234人
周文洪
【风趣的解释】
Abstract Factory Mode
请美眉去麦当劳吃汉堡,不同的美眉有不同的口味,要每个都记住是一件烦人的事情,我一般采用Factory Method Mode,带着美眉到服务员那儿,说“要一个汉堡”,具体要什么样的汉堡呢,让美眉直接跟服务员说就行了。
【正式的解释】
抽象工厂模式
核心工厂类不再负责所有产品的创建,而是将具体创建的工作交给子类去做,成为一个抽象工厂角色,仅负责给出具体工厂类必须实现的接口,而不接触哪一个产品类应当被实例化这种细节。
【Python版】
#-*- coding: utf-8 -*-
#汉堡抽象工厂
class HamburgerFactory(object):
def createHamburger(self):
pass
#汉堡里加辣椒的工厂
class HamburgerWithPepperFacotry(HamburgerFactory):
def createHamburger(self):
print "A hamburder with pepper is ready."
#汉堡里加火腿的工厂
class HamburgerWithHamFacotry(HamburgerFactory):
def createHamburger(self):
print "A hamburder with ham is ready."
#美眉A 喜欢吃辣椒
class MeiMeiA(object):
def getHamburder(self):
print "I want to a hanburger with pepper."
hamburgerFactory = HamburgerWithPepperFacotry()
hamburgerFactory.createHamburger()
#美眉B 喜欢吃火腿
class MeiMeiB(object):
def getHamburder(self):
print "I want to a hanburger with ham."
hamburgerFactory = HamburgerWithHamFacotry()
hamburgerFactory.createHamburger()
if __name__ == "__main__":
mA = MeiMeiA()
mA.getHamburder()
"""print out
I want to a hanburger with pepper.
A hamburder with pepper is ready.
"""
【JS版】
//汉堡抽象工厂
function HamburgerFactory(){
}
//汉堡里加辣椒的工厂
function HamburgerWithPepperFacotry(){
}
HamburgerWithPepperFacotry.prototype = new HamburgerFactory();
HamburgerWithPepperFacotry.prototype.constructor = HamburgerWithPepperFacotry;
HamburgerWithPepperFacotry.prototype.createHamburger = function(){
console.log("A hamburder with pepper is ready.");
}
//汉堡里加火腿的工厂
function HamburgerWithHamFacotry(){
}
HamburgerWithHamFacotry.prototype = new HamburgerFactory();
HamburgerWithHamFacotry.prototype.constructor = HamburgerWithHamFacotry;
HamburgerWithPepperFacotry.prototype.createHamburger = function(){
console.log("A hamburder with ham is ready.");
}
//美眉A 喜欢吃辣椒
function MeiMeiA(){
}
MeiMeiA.prototype.getHamburger = function(){
console.log("I want to a hanburger with pepper.");
hamburgerFactory = new HamburgerWithPepperFacotry();
hamburgerFactory.createHamburger();
}
//美眉B 喜欢吃火腿
function MeiMeiB(){
}
MeiMeiB.prototype.getHamburger = function(){
console.log("I want to a hanburger with ham.");
hamburgerFactory = new HamburgerWithHamFacotry();
hamburgerFactory.createHamburger();
}
var mA = new MeiMeiA();
mA.getHamburger();
/*console out
I want to a hanburger with pepper.
A hamburder with ham is ready.
*/