一、简单工厂模式

class Operation:  # Operation是抽象运算类
    numberA = 0
    numberB = 0
    def get_result(self):
        pass
class OperationAdd(Operation):  # 加法类
    def get_result(self):
        return self.numberA + self.numberB
class OperationSub(Operation):  # 减法类
    def get_result(self):
        return self.numberA - self.numberB
class OperationMul(Operation):  # 乘法类
    def get_result(self):
        return self.numberA * self.numberB
class OperationDiv(Operation):  # 除法类
    def get_result(self):
        return self.numberA / self.numberB
class OperationFactory:
    @staticmethod
    def create_operate(operate_name):
        oper = None
        if operate_name == '+':
            oper = OperationAdd()
        elif operate_name == '-':
            oper = OperationSub()
        elif operate_name == '*':
            oper = OperationMul()
        elif operate_name == '/':
            oper = OperationDiv()
        return oper
oper = OperationFactory.create_operate('-')
oper.numberA = 1
oper.numberB = 2
result = oper.get_result()
print(result)
其他语言
02-13 06:42