zoukankan      html  css  js  c++  java
  • 一起来学设计模式-----创建型模式之工厂方法

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

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

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

  • 相关阅读:
    LeetCode456. 132模式
    LeetCode455. 分发饼干
    LeetCode454. 四数相加 II
    LeetCode453. 最小移动次数使数组元素相等
    matchMedia 媒体查询结果
    异常捕获
    常用xpath选择器和css选择器总结
    python-爬虫中的extract()
    Python应用前景广阔,怎么学才能快速上手?
    Python 为什么要有 pass 语句?
  • 原文地址:https://www.cnblogs.com/loleina/p/7375525.html
Copyright © 2011-2022 走看看