[Python design mode] 1th Chapter Calculator--Simple Factory mode

Source: Internet
Author: User
Tags square root

Write it in front.
"""读书的时候上过《设计模式》这一门课,当时使用的教材是程杰老师的《大话设计模式》,使用的语言是C#,学过课程之后初期深感面向对象思想的伟大,但是很少应用到实际开发中。后来我接触了Python,现在工作中用到最多的也是Python,或许是因为Python的便利性,我写的很多脚本/程序都还是面向过程编程,缺少面向对象的思想在里边。因此,我打算重读程杰老师的《大话设计模式》并用Python进行实践。"""                                                                                                                                                                                                                                        by ZH奶酪——张贺
Topic

A calculator console program is implemented using an object-oriented language, which requires the input of two numbers and operation symbols (+-*/) to obtain the results.

Base version
a = int(input("input a number:"))b = str(input("input a operater(+ - * /):"))c = int(input("input a number:"))if b == "+":    print(a+c)elif b == "-":    print(a-c)elif b == "*":    print(a*c)else b == "/":    print(a/c)
input a number:16input a operater(+ - * /):*input a number:232
Comments
    1. Variable naming is not canonical
    2. Useless if condition to judge too much
    3. A case where the second number is 0 is not considered in the division operation
Improved version 1.0--specification code
number_a = int(input("input a number:"))operator = str(input("input a operater(+ - * /):"))number_b = int(input("input a number:"))if operator == "+":    print(number_a + number_b)elif operator == "-":    print(number_a - number_b)elif operator == "*":    print(number_a * number_b)elif operator == "/":    if number_b != 0:        print(number_a / number_b)    else:        print("With operator '/', the second number can not be zero.")else:    print("Wrong operator.")
input a number:12input a operater(+ - * /):/input a number:0With operator '/', the second number can not be zero.
Comments
    1. No use of object-oriented thinking
    2. Only meet the current requirements, difficult to maintain, easy to expand, not easy to reuse, not flexible
Why is movable printing able to be ranked four major inventions? is mainly the idea of its method.
    1. The article is easy to change word, can maintain
    2. One word can be reused, reusable
    3. Article easy to add word, extensible
    4. The article revision only need movable movable, the flexibility is good
Copy? Reuse?

If you make a calculator with a graphical interface, the above code needs to be written again. In order to avoid this, it is necessary to 业务逻辑 界面逻辑 separate and reduce the coupling degree.

Improved version 2.0--using encapsulation decoupling
class Operation():    def __init__(self):        self.result = None    def get_result(self, number_a, number_b, operator):        if operator == "+":            self.result = number_a + number_b        elif operator == "-":            self.result = number_a - number_b        elif operator == "*":            self.result = number_a * number_b        elif operator == "/":            if number_b != 0:                self.result = number_a / number_b            else:                print("With operator '/', the second number can not be zero.")        else:            print("Wrong operator.")        return self.resultnumber_a = int(input("input a number:"))operator = str(input("input a operater(+ - * /):"))number_b = int(input("input a number:"))operation = Operation()print(operation.get_result(number_a, number_b, operator))
input a number:12input a operater(+ - * /):+input a number:1224
Comments
    1. Only the encapsulation is used, and the inheritance and polymorphism are useless.
Tight coupling? Loose coupling?

If you want to support an open-root operation, the above code needs to change the functions including subtraction, the get_result subtraction operation should be separated, and one of them will not affect the other. Then you need to define a operator base class that will be get_result defined as a virtual function, and then implement subtraction four subclasses by inheritance and polymorphism, defining the implementation logic of the virtual function in each subclass.

Resources: Polymorphism and virtual functions in Python

Improved version 3.0--simple Factory mode
from abc import ABCMeta, abstractmethodclass Operation():    __metaclass__ = ABCMeta    def __init__(self):        self.result = None    @abstractmethod    def get_result(self):        pass    class AddOperation(Operation):        def get_result(self, number_a, number_b):        self.result = number_a + number_b        return self.result    class SubOperation(Operation):    def get_result(self, number_a, number_b):        self.result = number_a - number_b        return self.result    class MulOperation(Operation):    def get_result(self, number_a, number_b):        self.result = number_a * number_b        return self.result        class DivOperation(Operation):    def get_result(self, number_a, number_b):        if number_b == 0:            print("With operator '/', the second number can not be zero.")            return self.result        self.result = number_a / number_b        return self.result
How to instantiate?—— Simple Factory mode

Now the implementation logic of the subtraction is further isolated, and then even if an open square root operator is added, it is not related to subtraction. So how do you instantiate these classes? can be used 简单工厂模式 .

class OperationFactory():        @classmethod    def create_operate(self, operator):        oper = None        if operator == "+":            oper = AddOperation()        elif operator == "-":            oper = SubOperation()        elif operator == "*":            oper = MulOperation()        elif operator == "/":            oper = DivOperation()        else:            print("Wrong operator.")        return oper

The corresponding object can be instantiated by inputting the operation symbol through the simple factory above. Below is the code for the client.

number_a = int(input("input a number:"))operator = str(input("input a operater(+ - * /):"))number_b = int(input("input a number:"))oper = OperationFactory.create_operate(operator)print(oper.get_result(number_a, number_b))
input a number:12input a operater(+ - * /):-input a number:120
Comments
    1. The business logic is isolated from the interface logic and does not care whether it is a console program or a GUI program
    2. Different operation logic isolation, one operator's additions and deletions will not affect other operations
    3. The encapsulation, inheritance and polymorphism of object-oriented thinking are embodied
    4. Easy to maintain, easy to expand, easy to reuse

[Python design mode] 1th Chapter Calculator--Simple Factory mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.