Operation運算類別
# -*- coding: utf-8 -*-
class Operation(object):
def __init__(self):
self._numberA = 0
self._numberB = 0
@property
def numberA(self):
return self._numberA
@numberA.setter
def numberA(self, value):
self._numberA = value
@property
def numberB(self):
return self._numberB
@numberB.setter
def numberB(self, value):
self._numberB = value
def get_result(self):
#result = 0
#return result
raise NotImplementedError
加減乘除類別
# -*- coding: utf-8 -*-
from operation import Operation
class DivZeroException: pass
class OperationAdd(Operation):
def get_result(self):
result = 0
result = self._numberA + self._numberB
return result
class OperationSub(Operation):
def get_result(self):
result = 0
result = self._numberA - self._numberB
return result
class OperationMul(Operation):
def get_result(self):
result = 0
result = self._numberA * self._numberB
return result
class OperationDiv(Operation):
def get_result(self):
result = 0
if self._numberB == 0:
raise DivZeroException
result = self._numberA * 1.0 / self._numberB
return result
簡單運算工廠類別
# -*- coding: utf-8 -*-
from suboperation import OperationAdd, OperationSub, OperationMul, OperationDiv
class OperationFactory:
@staticmethod
def create_operate(operate):
oper = None
if operate:
if operate == '+':
oper = OperationAdd()
elif operate == '-':
oper = OperationSub()
elif operate == '*':
oper = OperationMul()
elif operate == '/':
oper = OperationDiv()
return oper
用戶端程式碼
# -*- coding: utf-8 -*-
from operation import Operation
from operationfactory import OperationFactory
oper = OperationFactory.create_operate('+')
oper.numberA = 1
oper.numberB = 2
result = oper.get_result()
print result
沒有留言:
張貼留言