Home > Article > Backend Development > 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.
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!")
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()
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()
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)
In summary, the Simple Factory pattern is all about creating a factory class that handles object(s) creation on behalf of a client.
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.
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.
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.
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.
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!")
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()
Step 3: Defining the Creator
... ... class AnimalFactory: def make_sound(self, animal_type): return eval(animal_type.title())().make_sound()
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)
And the client can utilize the solution as follows:
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def make_sound(self): pass
The Factory Method Pattern solution, allows clients to be able to extend the system and provide custom animal implementations if needed.
Decoupling: It decouples client code from the concrete classes, reducing dependencies and enhancing code stability.
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.
Extensibility: New product classes can be added without modifying existing code, promoting an open-closed principle.
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!