Skip to content

Instantly share code, notes, and snippets.

@Everfighting
Last active May 7, 2017 08:49
Show Gist options
  • Save Everfighting/084957cda37c1f3f494c056b688cc50f to your computer and use it in GitHub Desktop.
Save Everfighting/084957cda37c1f3f494c056b688cc50f to your computer and use it in GitHub Desktop.
大话设计模式:简单工厂模式(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:divided 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 = raw_input("operator: ")
opa = input("a: ")
opb = input("b: ")
factory = OperationFactory()
cal = factory.createOperation(op)
cal.op1 = opa
cal.op2 = opb
print cal.GetResult()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment