工厂方法模式Python版--雷锋依然在人间

来源:互联网 发布:2016淘宝女装店铺名字 编辑:程序博客网 时间:2024/05/18 22:42



简介

工厂方法模式定义了一个用于创建对象的接口,让子类决定实例化哪一个类,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 opif __name__ == "__main__":    oper = OperationFactory()    oper.GetResult("+")    oper.NumA = 1    oper.NumB = 2    print oper.GetResult()

用工厂模式实现计算器的UML关系图


class IFactory:    def CreateOperation(self):        passclass AddFactory(IFactory):    def CreateOperation(self):        add = OperationAdd()return addclass SubFactory(IFactory):    def CreateOperation(self):        sub = OperationSub()return subclass MulFactory(IFactory):    def CreateOperation(self):        mul = OperationMul()return mulclass DivFactory(IFactory):    def CreateOperation(self):        div = OperationDiv()return divif __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):    passclass Volunteer(LeiFeng):    pass

简单工厂模式的代码实现

class SimpleFactory:    def CreateLeiFeng(self, type):        if type is "Volunteer":            result = Volunteer()        elif type is "Undergraduate":            result = Undergraduate()        return resultif __name__ == "__main__":    s = SimpleFactory()    v = s.CreateLeiFeng("Volunteer")    v.Sweep()    v.Wash()
工厂模式的代码实现

class IFactory:    def CreateLeiFeng(self):        passclass 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()

工厂方法模式的优缺点

优点:

  1. 可在不知具体实现的情况下编程
  2. 更容易扩展对象---只要在已有代码中新加入一个子类提供的新的工厂方法实现,然后在客户端使用这个新的子类即可
  3. 连接平行的类层次----工厂方法除了创造产品对象外,在连接平行的类层次上也大显身手
缺点:

  1. 具体产品对象和工厂方法的耦合性

工厂方法需要创建产品对象的,也就是需要选择具体的产品对象,并创建他们的实例,因此具体产品对象和工厂方法是耦合的。

何时选用工厂方法模式

  1. 如果一个类需要创建某个接口对象,但不知道具体的实现,这个时候可以选用工厂方法模式,把创建对象的工作延迟到子类中去实现。
  2. 如果一个类本身是希望由它的子类来创建所需的对象的时候,应该使用工厂方法模式。

相关模式

  1. 工厂方法模式和简单工厂模式,以及抽象工厂模式
  2. 工厂方法模式和模板方法模式
工厂方法模式的子类专注于创建产品对象,而模板方法模式的子类专注于为固定算法骨架提供某些差异化步骤的实现。








0 0
原创粉丝点击