# 工厂方法

```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/10/7 8:27 PM
# @Author  : xinfa.jiang
# @Site    : 
# @File    : factory_method.py
# @Software: PyCharm

"""
工厂方法
定义一个用于创建对象的接口, 让子类决定实例化哪个类
工厂方法使一个类的实例化延迟到其子类
如果存在变更, 改creator即可
"""

from abc import ABCMeta, abstractmethod


class Product(object):
    """
    定义工厂方法所创建的对象接口
    """
    __metaclass__ = ABCMeta

    @abstractmethod
    def echo(self):
        pass


class ConcreteProductA(Product):
    """
    具体的产品, 实现了product的接口
    """

    def echo(self):
        print("product A")


class ConcreteProductB(Product):
    """
    具体的产品, 实现了product的接口
    """

    def echo(self):
        print("product B")


class Creator(object):
    """
    声明了工厂方法, 该方法返回一个Product类型的对象
    """
    __metaclass__ = ABCMeta

    @abstractmethod
    def create(self):
        pass


class ConcreteCreatorA(Creator):
    """
    重定义, 返回一个ConcreteProduct实例
    """

    def create(self):
        return ConcreteProductA()


class ConcreteCreatorB(Creator):
    def create(self):
        return ConcreteProductB()


if __name__ == '__main__':
    # 创建A工厂创建类
    factory_a = ConcreteCreatorA()
    # 创建一个A实例产品
    product = factory_a.create()
    product.echo()

    factory_b = ConcreteCreatorB()
    product = factory_b.create()
    product.echo()
```


---

# 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/factory_method.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.
