The Wayback Machine - http://web.archive.org/web/20240529114001/https://www.geeksforgeeks.org/factory-method-python-design-patterns/
Open In App

Factory Method – Python Design Patterns

Last Updated : 31 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Factory Method is a Creational Design Pattern that allows an interface or a class to create an object, but lets subclasses decide which class or object to instantiate. Using the Factory method, we have the best ways to create an object. Here, objects are created without exposing the logic to the client, and for creating the new type of object, the client uses the same common interface.
 

Problems we face without Factory Method:

Imagine you are having your own startup which provides ridesharing in different parts of the country. The initial version of the app only provides Two-Wheeler ridesharing but as time passes, your app becomes popular and now you want to add Three and Four-Wheeler ridesharing also. 
It’s a piece of great news! but what about the software developers of your startup. They have to change the whole code because now most part of the code is coupled with the Two-Wheeler class and developers have to make changes to the entire codebase. 
After being done with all these changes, either the developers end with the messy code or with the resignation letter. 
 

factory-pattern-python

Localizer app

 

Diagrammatic representation of Problems without using Factory Method

Let’s understand the concept with one more example which is related to the translations and localization of the different languages. 
Suppose we have created an app whose main purpose is to translate one language into another and currently our app works with 10 languages only. Now our app has become widely popular among people but the demand has grown suddenly to include 5 more languages. 
It’s a piece of great news! only for the owner not for the developers. They have to change the whole code because now most part of the code is coupled with the existing languages only and that’s why developers have to make changes to the entire codebase which is really a difficult task to do.
Let’s look at the code for the problem which we may face without using the factory method.
 

Note: Following code is written without using the Factory method. 

Python3




# Python Code for Object
# Oriented Concepts without
# using Factory method
 
class FrenchLocalizer:
 
    """ it simply returns the french version """
 
    def __init__(self):
 
        self.translations = {"car": "voiture", "bike": "bicyclette",
                             "cycle":"cyclette"}
 
    def localize(self, msg):
 
        """change the message using translations"""
        return self.translations.get(msg, msg)
 
class SpanishLocalizer:
    """it simply returns the spanish version"""
 
    def __init__(self):
 
        self.translations = {"car": "coche", "bike": "bicicleta",
                             "cycle":"ciclo"}
 
    def localize(self, msg):
 
        """change the message using translations"""
        return self.translations.get(msg, msg)
 
class EnglishLocalizer:
    """Simply return the same message"""
 
    def localize(self, msg):
        return msg
 
if __name__ == "__main__":
 
    # main method to call others
    f = FrenchLocalizer()
    e = EnglishLocalizer()
    s = SpanishLocalizer()
 
    # list of strings
    message = ["car", "bike", "cycle"]
 
    for msg in message:
        print(f.localize(msg))
        print(e.localize(msg))
        print(s.localize(msg))


Solution by Factory Method:

Its solution is to replace the straightforward object construction calls with calls to the special factory method. Actually, there will be no difference in the object creation but they are being called within the factory method.
For example Our Two_Wheeler, Three_Wheeler, and Four_wheeler classes should implement the ridesharing interface which will declare a method called a ride. Each class will implement this method uniquely.
 

python-factory-patter-solution

solution_factory_diagram

Now let us understand the factory method with the help of an example:

Python3




# Python Code for factory method
# it comes under the creational
# Design Pattern
 
class FrenchLocalizer:
 
    """ it simply returns the french version """
 
    def __init__(self):
 
        self.translations = {"car": "voiture", "bike": "bicyclette",
                             "cycle":"cyclette"}
 
    def localize(self, msg):
 
        """change the message using translations"""
        return self.translations.get(msg, msg)
 
class SpanishLocalizer:
    """it simply returns the spanish version"""
 
    def __init__(self):
        self.translations = {"car": "coche", "bike": "bicicleta",
                             "cycle":"ciclo"}
 
    def localize(self, msg):
 
        """change the message using translations"""
        return self.translations.get(msg, msg)
 
class EnglishLocalizer:
    """Simply return the same message"""
 
    def localize(self, msg):
        return msg
 
def Factory(language ="English"):
 
    """Factory Method"""
    localizers = {
        "French": FrenchLocalizer,
        "English": EnglishLocalizer,
        "Spanish": SpanishLocalizer,
    }
 
    return localizers[language]()
 
if __name__ == "__main__":
 
    f = Factory("French")
    e = Factory("English")
    s = Factory("Spanish")
 
    message = ["car", "bike", "cycle"]
 
    for msg in message:
        print(f.localize(msg))
        print(e.localize(msg))
        print(s.localize(msg))


Class Diagram for Factory Method:

Let’s look at the class diagram considering the example of ride-sharing. 
 

factory-pattern-class

Factory_pattern_class_diagram

 

Advantages of using Factory method: 

  1. We can easily add new types of products without disturbing the existing client code.
  2. Generally, tight coupling is being avoided between the products and the creator classes and objects.

Disadvantages of using Factory method:

  1. To create a particular concrete product object, the client might have to sub-class the creator class.
  2. You end up with a huge number of small files i.e, cluttering the files.
    • In a Graphics system, depending upon the user’s input it can draw different shapes like rectangles, Square, Circle, etc. But for the ease of both developers as well as the client, we can use the factory method to create the instance depending upon the user’s input. Then we don’t have to change the client code for adding a new shape.
    • On a Hotel booking site, we can book a slot for 1 room, 2 rooms, 3 rooms, etc. Here user can input the number of rooms he wants to book. Using the factory method, we can create a factory class Any Rooms which will help us to create the instance depending upon the user’s input. Again we don’t have to change the client’s code for adding the new facility.


Previous Article
Next Article

Similar Reads

Abstract Factory Method - Python Design Patterns
Abstract Factory Method is a Creational Design pattern that allows you to produce the families of related objects without specifying their concrete classes. Using the abstract factory method, we have the easiest ways to produce a similar type of many objects. It provides a way to encapsulate a group of individual factories. Basically, here we try t
4 min read
Accessing Web Resources using Factory Method Design Pattern in Python
A factory is a class for building other objects, where it creates and returns an object based on the passed parameters. Here, the client provides materials to the Factory class, and the Factory class creates and returns the products based on the given material. A Factory is not a design pattern, but it serves as a basis for the Factory Method Desig
4 min read
Implementing Web Crawler using Abstract Factory Design Pattern in Python
In the Abstract Factory design pattern, every product has an abstract product interface. This approach facilitates the creation of families of related objects that is independent of their factory classes. As a result, you can change the factory at runtime to get a different object – simplifies the replacement of the product families. In this design
5 min read
Observer method - Python Design Patterns
The observer method is a Behavioral design Pattern which allows you to define or create a subscription mechanism to send the notification to the multiple objects about any new event that happens to the object that they are observing. The subject is basically observed by multiple objects. The subject needs to be monitored and whenever there is a cha
4 min read
Composite Method - Python Design Patterns
Composite Method is a Structural Design Pattern which describes a group of objects that is treated the same way as a single instance of the same type of the objects. The purpose of the Composite Method is to Compose objects into Tree type structures to represent the whole-partial hierarchies. One of the main advantages of using the Composite Method
5 min read
Decorator Method - Python Design Patterns
Decorator Method is a Structural Design Pattern which allows you to dynamically attach new behaviors to objects without changing their implementation by placing these objects inside the wrapper objects that contains the behaviors. It is much easier to implement Decorator Method in Python because of its built-in feature. It is not equivalent to the
3 min read
Builder Method - Python Design Patterns
Builder Method is a Creation Design Pattern which aims to "Separate the construction of a complex object from its representation so that the same construction process can create different representations." It allows you to construct complex objects step by step. Here using the same construction code, we can produce different types and representatio
5 min read
Adapter Method - Python Design Patterns
Adapter method is a Structural Design Pattern which helps us in making the incompatible objects adaptable to each other. The Adapter method is one of the easiest methods to understand because we have a lot of real-life examples that show the analogy with it. The main purpose of this method is to create a bridge between two incompatible interfaces.
4 min read
Prototype Method - Python Design Patterns
Prototype Method is a Creational Design Pattern which aims to reduce the number of classes used for an application. It allows you to copy existing objects independent of the concrete implementation of their classes. Generally, here the object is created by copying a prototypical instance during run-time. It is highly recommended to use Prototype Me
5 min read
Bridge Method - Python Design Patterns
The bridge method is a Structural Design Pattern that allows us to separate the Implementation Specific Abstractions and Implementation Independent Abstractions from each other and can be developed considering as single entities.The bridge Method is always considered as one of the best methods to organize the class hierarchy. [caption width="800"]B
5 min read
Article Tags :
Practice Tags :