Home Backend Development Python Tutorial Understanding the Factory and Factory Method Design Patterns

Understanding the Factory and Factory Method Design Patterns

Nov 05, 2024 pm 03:01 PM

Understanding the Factory and Factory Method Design Patterns

What is a Factory class? A factory class is a class that creates one or more objects of different classes.

The Factory pattern is arguably the most used design pattern in Software engineering. In this article, I will be providing an in-depth explanation of the Simple Factory and the Factory Method design patterns using a simple example problem.

The Simple Factory Pattern

Let's say we're to create a system that supports two types of animals say Dog & cat, each of the animal classes should have a method that makes the type of sound of the animal. Now a client will like to use the system to make animal sounds based on the client's user input. A basic solution to the above problem can be written as follows:

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        print("Bhow Bhow!")

class Cat(Animal):
    def make_sound(self):
        print("Meow Meow!")
Copy after login
Copy after login

With this solution, our client will utilize the system like this

## client code
if __name__ == '__main__':
    animal_type = input("Which animal should make sound Dog or Cat?")
    if animal_type.lower() == 'dog':
        Dog().make_sound()
    elif animal_type.lower() == 'cat':
        Cat().make_sound()
Copy after login
Copy after login

Our solution will work fine, but Simple Factory Pattern says we can do better. Why? As you've seen in the client code above, the client will have to decide which of our animal classes to call at a time. Imagine the system having, say, ten different animal classes. You can already see how problematic it will be for our client to use the system.

So here Simple Factory pattern is simply saying instead of letting the client decide on which class to call, let's make the system decide for the client.

To solve the problem using the Simple Factory pattern, all we need to do is create a factory class with a method that takes care of the animal object creation.

...
...
class AnimalFactory:
    def make_sound(self, animal_type):
        return eval(animal_type.title())().make_sound()
Copy after login
Copy after login

With this approach, the client code becomes:

## client code
if __name__ == '__main__':
    animal_type = input("Which animal should make sound Dog or Cat?")
    AnimalFactory().make_sound(animal_type)
Copy after login
Copy after login

In summary, the Simple Factory pattern is all about creating a factory class that handles object(s) creation on behalf of a client.

Factory Method Pattern

Going back to our problem statement of having a system that supports only two types of animal (Dog & Cat), what if this limitation is removed and our system is willing to support any type of animal? Of course, our system could not afford to provide implementations for millions of animals. This is where the Factory Method Pattern comes to the rescue.

In Factory Method pattern, we define an abstract class or interface to create objects, but instead of the factory being responsible for the object creation, the responsibility is deferred to the subclass that decides the class to be instantiated.

Key Components of the Factory Method Pattern

  1. Creator: The Creator is an abstract class or interface. It declares the Factory Method, which is a method for creating objects. The Creator provides an interface for creating products but doesn’t specify their concrete classes.

  2. Concrete Creator: Concrete Creators are the subclasses of the Creator. They implement the Factory Method, deciding which concrete product class to instantiate. In other words, each Concrete Creator specializes in creating a particular type of product.

  3. Product: The product is another abstract class or interface. It defines the type of objects the Factory Method creates. These products share a common interface, but their concrete implementations can vary.

  4. Concrete Product: Concrete products are the subclasses of the Product. They provide the specific implementations of the products. Each concrete product corresponds to one type of object created by the Factory Method.

Below is how our system code will look like using the Factory Method pattern:

Step 1: Defining the Product

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        print("Bhow Bhow!")

class Cat(Animal):
    def make_sound(self):
        print("Meow Meow!")
Copy after login
Copy after login

Step 2: Creating Concrete Products

## client code
if __name__ == '__main__':
    animal_type = input("Which animal should make sound Dog or Cat?")
    if animal_type.lower() == 'dog':
        Dog().make_sound()
    elif animal_type.lower() == 'cat':
        Cat().make_sound()
Copy after login
Copy after login

Step 3: Defining the Creator

...
...
class AnimalFactory:
    def make_sound(self, animal_type):
        return eval(animal_type.title())().make_sound()
Copy after login
Copy after login

Step 4: Implementing Concrete Creators

## client code
if __name__ == '__main__':
    animal_type = input("Which animal should make sound Dog or Cat?")
    AnimalFactory().make_sound(animal_type)
Copy after login
Copy after login

And the client can utilize the solution as follows:

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass
Copy after login

The Factory Method Pattern solution, allows clients to be able to extend the system and provide custom animal implementations if needed.

Advantages of the Factory Method Pattern

  1. Decoupling: It decouples client code from the concrete classes, reducing dependencies and enhancing code stability.

  2. Flexibility: It brings in a lot of flexibility and makes the code generic, not being tied to a certain class for instantiation. This way, we’re dependent on the interface (Product) and not on the ConcreteProduct class.

  3. Extensibility: New product classes can be added without modifying existing code, promoting an open-closed principle.

Conclusion

The Factory Method design pattern offers a systematic way to create objects while keeping code maintainable and adaptable. It excels in scenarios where object types vary or evolve.

Frameworks, libraries, plug-in systems, and software ecosystems benefit from its power. It allows systems to adapt to evolving demands.

However, it should be used judiciously, considering the specific needs of the application and the principle of simplicity. When applied appropriately, the Factory Method pattern can contribute significantly to the overall design and architecture of a software system.

Happy coding!!!

The above is the detailed content of Understanding the Factory and Factory Method Design Patterns. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

See all articles