# 抽象工厂

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

抽象工厂模式
'''
from abc import ABCMeta, abstractmethod


class AbstractProductA(object):
    """
    抽象产品A, 可能拥有多种实现
    """

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return "ProductA: %s" % self.name


class AbstractProductB(object):
    """
    抽象产品B, 可能拥有多种实现
    """

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return "ProductB: %s" % self.name


class ConcreteProductA1(AbstractProductA):
    '''
    具体产品A1
    '''
    pass


class ConcreteProductA2(AbstractProductA):
    '''
    具体产品A2
    '''
    pass


class ConcreteProductB1(AbstractProductB):
    pass


class ConcreteProductB2(AbstractProductB):
    pass


class AbstractFactory(object):
    """
    抽象工厂接口, 包含所有产品创建的抽象方法
    __metaclass__参考：https://www.cnblogs.com/xybaby/p/7927407.html
    """
    __metaclass__ = ABCMeta

    @abstractmethod
    def create_product_a(self):
        pass

    @abstractmethod
    def create_product_b(self):
        pass


class ConcreteFactory1(AbstractFactory):
    """
    具体工厂, 创建具有特定实现的产品对象
    """

    def create_product_a(self):
        return ConcreteProductA1("PA1")

    def create_product_b(self):
        return ConcreteProductB1("PB1")


class ConcreteFactory2(AbstractFactory):
    def create_product_a(self):
        return ConcreteProductA2("PA2")

    def create_product_b(self):
        return ConcreteProductB2("PB2")


if __name__ == '__main__':
      # 抽象工厂先制造抽象实例，再通过抽象实例制造最终实例
    factory = ConcreteFactory2()

    product_a = factory.create_product_a()
    print(product_a)
#ProductA: PA2
```


---

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