码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-08-16 21:57:47      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:color   img   seo   name   使用   uml类图   ret   决定   设计模式   

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

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

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图,很快就能发现不同,简单的工厂在服务端有个方法,用于接收客户端的参数,从而实例化不同的对象,客户端只关心传入自己的参数,获取想要的对象即可。而工厂方法没有这个函数,客户端需要清楚知道自己要使用哪一个工厂。增加一个运算类时, 简单工厂是修改工厂类,而工厂方法是需要修改工厂类的,而工厂方法需要修改客户端

 

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

标签:color   img   seo   name   使用   uml类图   ret   决定   设计模式   

原文地址:http://www.cnblogs.com/loleina/p/7375525.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!