Factory Pattern

Share:

Factory Pattern is a creational design pattern that provides a generalized interface for creating objects, allowing the subclasses to decide which class to instantiate. It is uniquely suitable for situations where a class can't anticipate the type of objects it needs to create. Python, with its flexibility and high-level functionality, provides an efficient way to implement Factory Pattern. In this tutorial, we will take a deeper look into Python Factory Pattern, examine its structure, and see it in action through code snippets.

Factory pattern in Python consists of two principal components: a Creator and a Product. The Creator is a class with a method (usually named 'factory method') that creates and returns product objects. The Product is an interface for the kind of objects the factory method creates.

The basic structure of Factory pattern in Python is presented below:

class Product:
    def __init__(self):
        raise NotImplementedError

    def operation(self):
        raise NotImplementedError

class ConcreteProduct(Product):
    def __init__(self):
        pass  # Initialize any resources needed.
        
    def operation(self):
        pass  # Implementation of method.

class Creator:
    def create_product(self):
        return ConcreteProduct()

Here, 'Product' represents an interface for creating objects in a superclass. 'ConcreteProduct' overrides the operation() method declared in Product class. 'Creator' implements create_product() factory method that returns a new instance of ConcreteProduct.

Now, let's create a working example to illustrate Factory Pattern in Python:

class Dog:
    def __init__(self, name):
        self._name = name

    def speak(self):
        return "Woof!"

class Cat:
    def __init__(self, name):
        self._name = name

    def speak(self):
        return "Meow!"

def get_pet(pet="dog"):
     pets = dict(dog=Dog("Hope"), cat=Cat("Peace"))
     return pets[pet]

d = get_pet("dog")
print(d.speak())

c = get_pet("cat")
print(c.speak())

In the above code snippet, 'Dog' and 'Cat' are product classes and get_pet function is the factory function which creates and returns an instance of these classes based on the input argument.

The Factory Pattern ensures that a client is independent of how the products it gets created and represented. It only needs to get the appropriate product from the Factory and use it abstractly. Python's dynamic typing comes in handy while implementing such Design patterns.

Factory pattern provides an elegant way to solve complex object creation scenarios. It promotes loose-coupling by eliminating the need for binding application-specific classes into the code. The code only deals with the interface, thus allowing the user to derive new types without modifying existing code. Through the use of Factory Pattern, the system becomes more flexible, adaptable, and maintainable.

Simply put, Factory Pattern provides a simple way of creating and managing the lifecycle of objects while effectively encapsulating and decoupling the client code from the object implementation. Thus, allowing the code to focus on the underlying logic without worrying about the details of object creation, initialization, and destruction.

0 Comment


Sign up or Log in to leave a comment


Recent job openings