Last active
May 7, 2017 08:49
-
-
Save Everfighting/084957cda37c1f3f494c056b688cc50f to your computer and use it in GitHub Desktop.
大话设计模式:简单工厂模式(python版)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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