1. 程式人生 > >一種工廠模式的實現:python

一種工廠模式的實現:python

一、基本工廠模式

  工廠模式最簡單的實現是這樣的:


  python程式碼實現:
class Operation: 
    def GetResult(self):
        pass

class OperationAdd(Operation):
    def GetResult(self):
        return self.op1 + self.op2

class OperationSub(Operation):
    def GetResult(self):
        return self.op1 - self.op2

class OperationMul(Operation):
    def GetResult(self):
        return self.op1 * self.op2

class OperationDiv(Operation):
    def GetResult(self):
        try:
            result = self.op1 / self.op2
            return result
        except:
            print 'error while divide by zero'
            return 0

class OperationUndef(Operation):
    def GetResult(self):
        print 'Undefine operation.'
        return 0

class OperationFactory():
    operation = {}
    operation['+'] = OperationAdd()
    operation['-'] = OperationSub()
    operation['*'] = OperationMul()
    operation['/'] = OperationDiv()

    def createOperation(self, ch):
        if ch in self.operation:
            op = self.operation[ch]
        else:
            op = OperationUndef()
        return op

if __name__ == '__main__':
    op = '+'
    opa = 12
    opb = 21
    factory = OperationFactory()
    ca1 = factory.createOperation(op)
    ca1.op1 = opa
    ca1.op2 = opb
    print ca1.GetResult()


二、另外一種形式的工廠模式   程式碼結構
  所有的類和方法定義在Classes Set中的py檔案中,中間使用的方法central_call集中整合這些類的方法,一共外層呼叫者使用。   通過下面的程式碼會更容易理解它:   類定義:operation.py
class Operators(object):
 def __init__(self):
  pass

 def add(self, op1, op2, status=None):
  return op1 + op2

 def sub(self, op1, op2, status=None):
  return op1 - op2

  CentralCall: centralCall.py
from operation import Operators

operators = Operators()

def centralCall(cf, func, *args):
 status = []
 ret = getattr(globals()[cf], func)(*args, status=status)
 if status:
  print status
 return ret

  外部呼叫:test.py
from CentralCall import centralCall

op1 = 5
op2 = 10
op3 = 0
ret = centralCall('operators', 'add', op1, op2)
print ret

三、總結 這類工廠模式主要是利用了python內建的getattr方法來呼叫各個類的方法,在實際應用中還是比較實用的。