您的位置:首页 > 其它

一起来学设计模式-----创建型模式之工厂方法

2017-08-16 20:23 579 查看
工厂方法模式,在简单工厂上再深一层,简单工厂里有一个弊端,就是在方法里是根据用户的输入直接返回子类对象。在工厂方法里,定义了一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使得一个类的实例化延迟到了子类。

以之前的操作运算为例,使用工厂方法代码如下:

from abc import ABCMeta, abstractmethod

class BaseOperation:
def GetResult(self,a,b):
result = 0
return result

class OperationAdd(BaseOperation):
def __int__(self,a,b):
self.a = a
self.b = b

def GetResult(self,a,b):
result = 0
result = a + b
return result

class OperationSub(BaseOperation):
def __int__(self,a,b):
self.a = a
self.b = b

def GetResult(self,a,b):
result = 0
result = a - b
return result

class OperationMul(BaseOperation):
def GetResult(self,a,b):
result = 0
result = a * b
return result

class OperationDiv(BaseOperation):
def GetResult(self,a,b):
result = 0
if b == 0 :
raise ValueError("no 0 !")
result = a/b
return result

class IFactory:
@abstractmethod
def  CreateOperation(self):
pass

class AddFactory(IFactory):
def CreateOperation(self):
return OperationAdd()

class SubFactory(IFactory):
def CreateOperation(self):
return OperationSub()

class MulFactory(IFactory):
def CreateOperation(self):
return OperationMul()

class DivFactory(IFactory):
def CreateOperation(self):
return OperationDiv()

def main():
operFactory = AddFactory()
oper = operFactory.CreateOperation()
print oper.GetResult(2,4)

if __name__ == '__main__':
main()


客户端在使用时,需要决定由于哪一个工厂来实例化类,每个类都有自己的工厂,选择好工厂,就能实例化得到这个工程所有的类。此时如果需要增加一个运行操作,完全不需要修改其他的业务逻辑,增加运算类和自己的工厂即可。UML类图如下所示



  

对比两个模式下的UML图,很快就能发现不同,简单的工厂在服务端有个方法,用于接收客户端的参数,从而实例化不同的对象,客户端只关心传入自己的参数,获取想要的对象即可。而工厂方法没有这个函数,客户端需要清楚知道自己要使用哪一个工厂。增加一个运算类时, 简单工厂是修改工厂类,而工厂方法是需要修改工厂类的,而工厂方法需要修改客户端
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: