# 简单工厂模式

```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/10/7 4:33 PM
# @Author  : xinfa.jiang
# @Site    : 
# @File    : simple_factory.py
# @Software: PyCharm
'''
简单工厂模式
'''


class Operation(object):
    '''
    property也是class
    @property装饰器负责把一个方法变成属性
    '''

    @property
    def number_a(self):
        return self.__number_a

    @number_a.setter
    def number_a(self, value):
        self.__number_a = value

    @property
    def number_b(self):
        return self.__number_b

    @number_b.setter
    def number_b(self, value):
        self.__number_b = value


class OperationAdd(Operation):
    '''
    继承Operation，实现+操作
    '''

    def get_result(self):
        return self.number_a + self.number_b


class OperationSub(Operation):
    '''
    -操作
    '''

    def get_result(self):
        return self.number_a - self.number_b


class OperationFactory(object):
    '''
    根据输入的operate符号，创建不同的类，这些类都继承Operation
    '''

    @staticmethod
    def create_operation(operate):
        if operate == "+":
            return OperationAdd()
        elif operate == "-":
            return OperationSub()


if __name__ == '__main__':
    # 调用静态方法，直接用，不需要创建()对象。简单工厂直接制造的operation实例
    op = OperationFactory.create_operation('-')
    op.number_a = 10
    op.number_b = 5

    print(op.get_result())
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/pattern/simple_factory.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
