"Westward design mode" - a simple factory pattern (Python Edition)

简单工厂模式(Simple Factory Pattern): Is defined by a specialized class is responsible for creating instances of other classes, instances are created usually have a common parent class.

Example:

Python console designed using a calculator, requires two input operands and symbols, to obtain an operation result.

1. Beginners wording

class Operation(object):

    def __init__(self):
        pass

    def conver_strNumber(self, strNumber):
        '''
        将字符串格式的数字,转化成对应格式的数字
        :param strNumber:
        :return:
        '''
        if '.' not in strNumber:
            return int(strNumber)
        else:
            return float(strNumber)

    def op(self, strNumberA, strNumberB, strOperate):
        if strOperate == '+':
            return self.conver_strNumber(strNumberA) + self.conver_strNumber(strNumberB)
        elif strOperate == '-':
            return self.conver_strNumber(strNumberA) - self.conver_strNumber(strNumberB)
        elif strOperate == '*':
            return self.conver_strNumber(strNumberA) * self.conver_strNumber(strNumberB)
        elif strOperate == '/':
            if strNumberB != '0' and strNumberB != '0.0':
                return self.conver_strNumber(strNumberA) / self.conver_strNumber(strNumberB)
            else:
                return 0
        else:
            print('只能做加减乘除运算')

if __name__ == '__main__':
    p = Operation()
    print(p.op('2.2', '1', '+'))
    
# 输出
21.2

Analysis : The wording of the above, the addition and subtraction multiplication and division in a class all to achieve, although to achieve a calculator function, but increases other operations or modify certain operations must be modified in the Operation class. Such that the program is not easy to maintain, spreading and multiplexing and coupling high .

2. Use simple factory pattern

# Operation运算类
class Operation(object):
    def __init__(self, strNumberA=0, strNumberB=0):
        self.NumberA = strNumberA
        self.NumberB = strNumberB

    def conver_strNumber(self, strNumber):
        '''
        将字符串格式的数字,转化成对应格式的数字
        :param strNumber:
        :return:
        '''
        if '.' not in strNumber:
            return int(strNumber)
        else:
            return float(strNumber)

    def GetResult(self):
        pass


# 加法运算类
class OperationAdd(Operation):
    def GetResult(self):
        return self.conver_strNumber(self.NumberA) + self.conver_strNumber(self.NumberB)


# 减法运算类
class OperationSub(Operation):
    def GetResult(self):
        return self.conver_strNumber(self.NumberA) - self.conver_strNumber(self.NumberB)


# 乘法运算类
class OperationMul(Operation):
    def GetResult(self):
        return self.conver_strNumber(self.NumberA) * self.conver_strNumber(self.NumberB)


# 除法运算类
class OperationDiv(Operation):
    def GetResult(self):
        if self.NumberB != 0 and self.NumberB != 0.0:
            return self.conver_strNumber(self.NumberA) / self.conver_strNumber(self.NumberB)
        else:
            return '除数不能为0'

# 其他操作符运算
class OperationUndef(Operation):
    def GetResult(self):
        return '操作符错误'


# 简单工厂类
class OperationFactory(object):
    def createOperate(self, operate):
        if operate == '+':
            return OperationAdd()
        elif operate == '-':
            return OperationSub()
        elif operate == '*':
            return OperationMul()
        elif operate == '/':
            return OperationDiv()
        else:
            return OperationUndef()

if __name__ == '__main__':

    strNumA = '1.0'
    strNumB = '2'
    oper = '/'

    OP = OperationFactory()
    oper_obj = OP.createOperate(oper)
    oper_obj.NumberA = strNumA
    oper_obj.NumberB = strNumB
    result = oper_obj.GetResult()
    print(result)
    
# 输出
0.5

Analysis : The various calculations split into separate classes, each class inherits Operation in each operation a subclass overrides GetResult () Method of Operation class. Unified by simple factory class (OperationFactory class) class instantiation operator required operation.

The advantage of this design:

  • Easy to expand

    If you add a new operator class, just

    1. The new class inherits Operation class operation, and override GetResult () method
    2. Add simple if statement corresponding factory class (OperationFactory class)

    No action is required other operation type.

  • Easy to maintain

    Modify the operation of a class, the class does not involve other operations, due largely to avoid the misuse and other operations modify the class of problems.

  • Low coupling

    Each operator class only public inheritance Operation class, the class does not involve other operations.

  • High multiplexed

    Whether it is the console or windows programs, Web program, the program can be used to achieve calculator functions.


If useful for you, welcome to scan the next Fanger Wei code number of public concern, we will continue to output the wonderful original article, and you better learn Python, easy to use, fun knowledge together.

Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/ghostlee/p/12079488.html