Logo

dev-resources.site

for different kinds of informations.

Understanding the Factory and Factory Method Design Patterns

Published at
11/4/2024
Categories
designpatterns
factory
python
programming
Author
mameen
Author
6 person written this
mameen
open
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!")
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Step 2: Creating Concrete Products

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

class Cat(Animal):
    def make_sound(self):
        print("Meow Meow!")
Enter fullscreen mode Exit fullscreen mode

Step 3: Defining the Creator

class AnimalFactory(ABC):
    @abstractmethod
    def create_animal(self):
        pass
Enter fullscreen mode Exit fullscreen mode

Step 4: Implementing Concrete Creators

class DogFactory(AnimalFactory):
    def create_animal(self):
        return Dog()

class CatFactory(AnimalFactory):
    def create_animal(self):
        return Cat()
Enter fullscreen mode Exit fullscreen mode

And the client can utilize the solution as follows:

## client code
def get_animal(animal_type):
    animals = {
        "dog": DogFactory,
        "cat": CatFactory,
    }

    return animals[animal_type]().creat_animal()

if __name__ == '__main__':
    animal_type = input("Which animal should make sound Dog or Cat?")
    animal = get_animal(animal_type.lower())
    animal.make_sound()
Enter fullscreen mode Exit fullscreen mode

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!!!

factory Article's
25 articles in total
Favicon
Clojure is Awesome!!!
Favicon
Understanding the Factory and Factory Method Design Patterns
Favicon
Factory Design Pattern
Favicon
Things You Want to Ensure When Factory Resetting Your HP Laptop Without a Password
Favicon
The Factory Pattern in C#: Creating Objects the Smart Way
Favicon
Enhance Your Factory Car Radio's Bass with Affordable Upgrades
Favicon
Page Object Model and Page Factory in Selenium
Favicon
Factory functions with private variables in JavaScript
Favicon
Evoluindo nosso Projeto Rails: Integrando o Padrão Factory para Maior Flexibilidade e Organização
Favicon
Javascript Factory Design Pattern
Favicon
Dart Abstract and Factory Keywords
Favicon
Azure Data Factory Overview For Beginners
Favicon
Improve your factories in Symfony
Favicon
Reduzindo a quantidade de Branchs na criação de Objetos com uma estrutura plugável
Favicon
Java 9 Factory Method for Collections: List, Set, Map
Favicon
How to implement simple Factory Pattern in Node.js
Favicon
Factory Design Pattern (simple example implementation in PHP)
Favicon
Spring's FactoryBean Interface
Favicon
Custom Validators for Angular Reactive Forms
Favicon
Design Patterns: Factory
Favicon
Creating objects dynamically with factory pattern in javascript
Favicon
Is this the real life, is this just fantasy?
Favicon
Design Patterns: Factory Pattern, Part 2
Favicon
Patterns in Kotlin: Abstract Factory
Favicon
SUT Factory

Featured ones: