Design Pattern-Creation-Factory Method Pattern

Factory method pattern

Overview

  • Define an interface for creating objects and let the subclass decide which product class to instantiate

Character

  • Abstract factory role (Creator)
  • Concrete Factory Role (Concrete Creator)
  • Abstract product role (Product)
  • Concrete Product Role

example

from abc import ABCMeta,abstractmethod

class Animal(metaclass=ABCMeta):
    
    @abstractmethod
    def walk(self):
        pass

class Rabbit(Animal):
    def walk(self):
        print("兔子行走")

class Duck(Animal):
    def walk(self):
        print("鸭子行走")

class AnimalFactory(metaclass=ABCMeta):
    @abstractmethod
    def create_animal(self):
        pass

class RabbitFactory(AnimalFactory):
    def create_animal(self):
        return Rabbit()

class DuckFactory(AnimalFactory):
    def create_animal(self):
        return Duck()

advantage

  • Each specific product corresponds to a specific factory class, no need to modify the factory class code
  • Hidden object creation implementation details

Disadvantage

  • Every time a specific product category is added, a corresponding specific factory category must be added

Guess you like

Origin blog.csdn.net/DALAOS/article/details/113179100