简介
工厂方法模式定义了一个用于创建对象的接口,让子类决定实例化哪一个类,Factory Method使一个雷的实例化延迟到其子类。
工厂方法模式的本质就是延迟到子类来选择是实现。
代码实现
class OperationFactory:
operators = {}
operators['+'] = OperationAdd()
operators['-'] = OperationSub()
operators['*'] = OperationMul()
operators['/'] = OperationDiv()
def GetResult(self, ch):
if ch in operators:
op = operators[ch]
else:
op = UndefOperator()
return op
if __name__ == "__main__":
oper = OperationFactory()
oper.GetResult("+")
oper.NumA = 1
oper.NumB = 2
print oper.GetResult()
用工厂模式实现计算器的UML关系图
class IFactory:
def CreateOperation(self):
pass
class AddFactory(IFactory):
def CreateOperation(self):
add = OperationAdd()
return add
class SubFactory(IFactory):
def CreateOperation(self):
sub = OperationSub()
return sub
class MulFactory(IFactory):
def CreateOperation(self):
mul = OperationMul()
return mul
class DivFactory(IFactory):
def CreateOperation(self):
div = OperationDiv()
return div
if __name__ == "__main__":
af = AddFactory()
oper = add.CreateOperation()
oper.NumA = 1
oper.NumB = 2
print oper.GetResult()
简单工厂模式最大的优点在于:工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态的实现实例化相关的类,对于客户端来说,去除了与躯体产品的依赖。
工厂模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,工厂方法把简单工厂的内部逻辑移到了客户端代码进行。你想要加功能,本来是改工厂类的,现在是修改客户端。
雷锋工厂
class LeiFeng:
def Sweep(self):
print "Sweep"
def Wash(self):
print "Wash"
def BuyRice(self):
print "Buy rice"
class Undergraduate(LeiFeng):
pass
class Volunteer(LeiFeng):
pass
简单工厂模式的代码实现
class SimpleFactory:
def CreateLeiFeng(self, type):
if type is "Volunteer":
result = Volunteer()
elif type is "Undergraduate":
result = Undergraduate()
return result
if __name__ == "__main__":
s = SimpleFactory()
v = s.CreateLeiFeng("Volunteer")
v.Sweep()
v.Wash()
工厂模式的代码实现
class IFactory:
def CreateLeiFeng(self):
pass
class UndergraduateFactory(IFactory):
def CreateLeiFeng(self):
return Undergraduate()
class VolunteerFactory(IFactory):
def CreateLeiFeng(self):
return Volunteer()
if __name__ == "__main__":
f = UndergraduateFactory()
u = f.CreateLeiFeng()
u.Sweep()
u.Wash()
工厂方法模式的优缺点
优点:
- 可在不知具体实现的情况下编程
- 更容易扩展对象---只要在已有代码中新加入一个子类提供的新的工厂方法实现,然后在客户端使用这个新的子类即可
- 连接平行的类层次----工厂方法除了创造产品对象外,在连接平行的类层次上也大显身手
- 具体产品对象和工厂方法的耦合性
工厂方法需要创建产品对象的,也就是需要选择具体的产品对象,并创建他们的实例,因此具体产品对象和工厂方法是耦合的。
何时选用工厂方法模式
- 如果一个类需要创建某个接口对象,但不知道具体的实现,这个时候可以选用工厂方法模式,把创建对象的工作延迟到子类中去实现。
- 如果一个类本身是希望由它的子类来创建所需的对象的时候,应该使用工厂方法模式。
相关模式
- 工厂方法模式和简单工厂模式,以及抽象工厂模式
- 工厂方法模式和模板方法模式