python实现简单工厂模式

#基础
import abc
class OperationBase(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def __init__(self, num_1, num_2):
        self.__num1 = num_1
        self.__num2 = num_2

    @property
    def num_1(self):
        return self.__num1

    @property
    def num_2(self):
        return self.__num2

    @abc.abstractmethod
    def calculate(self):
        pass

#加法类

from operation.operation_base import OperationBase
class OperationAdd(OperationBase):
    def __init__(self, num1, num2):
        super().__init__(num1, num2)

    def calculate(self):
        return super().num_1 + super().num_2

#减法类

from operation.operation_base import OperationBase
class OperationSub(OperationBase):
    def __init__(self, num1, num2):
        super().__init__(num1, num2)

    def calculate(self):
        return super().num_1 - super().num_2

#工厂类
from operation.operation_add import OperationAdd
from operation.operation_sub import OperationSub
class OperationFactory(object):
    dics = {'+': OperationAdd, '-': OperationSub}

    @classmethod
    def get_operation(cls, operator):
        if operator in cls.dics:
            return cls.dics.get(operator)
        else:
            raise Exception('该算法未实现')
#方法调用
from operation.operation_factory import OperationFactory

operation = OperationFactory.get_operation('-')(1,2)
print(operation.calculate())

你可能感兴趣的:(python实现简单工厂模式)