Design Pattern #Factory Method

I practiced design patterns so that I could write code that was conscious of design. Other Design Patterns will be released frequently.

Preface

The primary goal is to understand when, what, and how to use design patterns. (I'm new to Java or a statically typed language, and I don't have a long history of python, so I think there are some things that aren't like Pythonista. If you have any suggestions, please teach me.)

This time, the creational pattern FactoryMethod.

What is Factory Method?

Separate the object creation interface and the object creation role, replace the constructors of other classes with your own methods that can be overwritten by subclasses, and leave the object creation to the subclasses to improve the reusability of the class.

Overview

This sample program is based on a factory that makes identification cards (ID cards). There are four classes here.

The Product and Factory classes belong to a package called Framework. These two classes act as a framework for instantiation.

The ID and IDCardFactory classes do the actual fleshing. These belong to a package called ID Card.

Overall class diagram

Framework/factory.py


from abc import ABCMeta, abstractmethod


class Factory(metaclass=ABCMeta):

    @abstractmethod
    def _create_product(self, owner):
        pass

    @abstractmethod
    def _register_product(self, product):
        pass

    def create(self, owner):
        self.__p = self._create_product(owner)
        self._register_product(self.__p)
        return self.__p

The Template Method pattern is used here. The Template Method pattern is that "a superclass determines a large framework for processing, and a subclass determines the specific processing".

This class defines a large framework for processing, and subclasses are responsible for implementing both create_product and register_product methods for which specific processing has not been decided.

The create method uses both the create_product and register_product methods to create an instance of the "product". The Factory Method pattern uses the Template Method pattern for instantiation.

Framework/product.py


from abc import ABCMeta, abstractmethod

class Product(metaclass=ABCMeta):

    @abstractmethod
    def use(self):
        pass

Only the declaration of the abstract method use.

IDCard/idcard.py


from Framework.product import Product


class IDCard(Product):

    def __init__(self, owner):
        self.__owner = owner
        print(self.__owner + 'Create a card for')

    def use(self):
        print(self.__owner + 'Use the card')

    def get_owner(self):
        return self.__owner

Define as a subclass of Product class, create a constructor, and define use method and get_owner method.

IDCard/idcard_factory.py


from Framework.factory import Factory
from IDCard.idcard import IDCard


class IDCardFactory(Factory):

    def __init__(self):
        self.__registed = []

    def _create_product(self, owner):
        return IDCard(owner)

    def _register_product(self, product):
        self.__registed.append(product.get_owner())

Implemented create_product and register_product methods. The create_product method creates an instance of the IDCard class. The register_product method adds the owner of the IDCard obtained by the get_owner method to the list owners.

main.py


from IDCard.idcard_factory import IDCardFactory


def main():
    factory = IDCardFactory()
    card1 = factory.create('Hiroshi Yuki')
    card2 = factory.create('Tomura')
    card3 = factory.create('Hanako Sato')

    card1.use()
    card2.use()
    card3.use()

if __name__ == '__main__':
    main()

Output result

Create a card for Hiroshi Yuki
Create a Tomura card
Create a card for Hanako Sato
I will use Hiroshi Yuki's card
I will use Tomura's card
I will use Hanako Sato's card

Summary

Since only the interface is specified and the subclass is in charge of which class to instantiate, I was able to access the method from the outside without worrying about the internal implementation.

reference

Recommended Posts

Design Pattern #Factory Method
Design Pattern #Template Method
[Gang of Four] Design pattern learning --Factory Method
Learn the design pattern "Factory Method" in Python
Python Design Pattern --Template method
Design Pattern #Builder
Design Pattern #Adapter
Design Pattern #Decorator
Design Pattern #Observer
Design Pattern #Facade
Design Pattern #Strategy
Design Pattern #Singleton
Design Pattern #Proxy
[Gang of Four] Design pattern learning --Abstract Factory
Learn the design pattern "Abstract Factory" in Python
Learn the design pattern "Template Method" in Python
[Details] Template Method pattern
[Gang of Four] Design pattern learning --Template Method
I wrote a design pattern in kotlin Factory edition
Template Method pattern in Java
Ore Ore Design Pattern: Glocal Variable
[Gang of Four] Design pattern learning
Introduction of data-driven controller design method
GoF java design pattern rough summary
Design patterns to enjoy with frequently used Java libraries --Abstract Factory pattern
Learn the design pattern "Prototype" in Python
Learn the design pattern "Builder" in Python
[Gang of Four] Design pattern learning --Singleton
[Gang of Four] Design Pattern Learning --Decorator
[Gang of Four] Design pattern learning --Visitor
[Gang of Four] Design pattern learning --Mediator
Learn the design pattern "Flyweight" in Python
Learn the design pattern "Observer" in Python
Learn the design pattern "Memento" in Python
Learn the design pattern "Proxy" in Python
Learn the design pattern "Command" in Python
[Gang of Four] Design pattern learning --Iterator
GoF design pattern from the problem 2. Structure
Learn the design pattern "Visitor" in Python
Learn the design pattern "Bridge" in Python
Learn the design pattern "Mediator" in Python
Learn the design pattern "Decorator" in Python
[Gang of Four] Design pattern learning --Facade
[Gang of Four] Design pattern learning --Composite
[Gang of Four] Design pattern learning --Prototype
GoF design pattern from the problem 1. Generation
Learn the design pattern "Iterator" in Python
[Gang of Four] Design pattern learning --Memento
[Gang of Four] Design pattern learning --State
[Gang of Four] Design pattern learning --Interpreter
[Gang of Four] Design pattern learning --Builder
Learn the design pattern "Strategy" in Python
[Gang of Four] Design pattern learning --Bridge
Learn the design pattern "Composite" in Python
Learn the design pattern "Singleton" with Python
Learn the design pattern "State" in Python
Learn the design pattern "Adapter" in Python
[Gang of Four] Design pattern learning --Proxy
[Gang of Four] Design pattern learning --Strategy
[Gang of Four] Design pattern learning --Adapter
Learn the design pattern "Facade" with Python