🏭

Factory Methodパターンを学ぶ【Python】

2022/02/06に公開

一言で言うと

どのクラスをインスタンス化すべきかどうかをサブクラス側に任せる。

コードサンプル

ディレクトリ構造
factory_method
├── framework
│   ├── factory.py
│   └── product.py
├── idcard
│   ├── idcard.py
│   └── idcard_factory.py
└── main.py
main.py
from framework.factory import Factory
from framework.product import Product
from idcard.idcard_factory import IDCardFactory


def main() -> None:
    factory: Factory = IDCardFactory()
    card1: Product = factory.create('user1')
    card2: Product = factory.create('user2')
    card3: Product = factory.create('user3')
    card1.use()
    card2.use()
    card3.use()


if __name__ == '__main__':
    main()
factory.py
from abc import ABCMeta, abstractmethod
from typing import final
from .product import Product


class Factory(metaclass=ABCMeta):
    @final
    def create(self, owner: str) -> Product:
        p: Product = self._createProduct(owner)
        self._registerProduct(p)
        return p

    @abstractmethod
    def _createProduct(self, owner: str) -> Product:
        pass

    @abstractmethod
    def _registerProduct(self, product: Product) -> None:
        pass
product.py
from abc import ABCMeta, abstractmethod


class Product(metaclass=ABCMeta):
    @abstractmethod
    def use() -> None:
        pass
idcard_factory.py
from framework.factory import Factory
from framework.product import Product
from .idcard import IDCard


class IDCardFactory(Factory):
    __onwers = []

    def _createProduct(self, owner: str) -> Product:
        return IDCard(owner)

    def _registerProduct(self, product: Product) -> None:
        self.__onwers.append(product.getOwner())

    def getOnwer(self) -> list:
        return self.__onwers
idcard.py
from framework.product import Product


class IDCard(Product):
    def __init__(self, owner: str) -> None:
        print(f'{owner}のカードを作ります')
        self.owner: str = owner

    def use(self) -> None:
        print(f'{self.owner}のカードを使います')

    def getOwner(self) -> str:
        return self.owner

参考文献

実践python3
増補改訂版Java言語で学ぶデザインパターン入門

Discussion