0
0
LldConceptBeginner · 3 min read

Factory Pattern: What It Is and How It Works

The Factory Pattern is a design pattern that creates objects without exposing the creation logic to the client. It provides a common interface to create different types of objects, letting subclasses decide which class to instantiate.
⚙️

How It Works

Imagine you want to buy a toy, but you don't want to know how the toy is made or which factory makes it. You just ask a toy store to give you the toy you want. The Factory Pattern works similarly in programming. Instead of creating objects directly, you ask a factory to create them for you.

This pattern hides the details of object creation from the user. The factory decides which specific class to create based on input or configuration. This way, the code that uses the objects doesn't need to change if new types of objects are added later.

💻

Example

This example shows a simple factory that creates different types of shapes based on a given name.

python
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def draw(self):
        pass

class Circle(Shape):
    def draw(self):
        print("Drawing a circle")

class Square(Shape):
    def draw(self):
        print("Drawing a square")

class ShapeFactory:
    @staticmethod
    def create_shape(shape_type: str) -> Shape:
        if shape_type == "circle":
            return Circle()
        elif shape_type == "square":
            return Square()
        else:
            raise ValueError(f"Unknown shape type: {shape_type}")

# Client code
shape1 = ShapeFactory.create_shape("circle")
shape1.draw()
shape2 = ShapeFactory.create_shape("square")
shape2.draw()
Output
Drawing a circle Drawing a square
🎯

When to Use

Use the Factory Pattern when your code needs to create objects but you want to keep the creation logic separate and flexible. It is helpful when:

  • You have multiple related classes and want to decide which one to create at runtime.
  • You want to avoid tight coupling between the code that uses objects and the classes that create them.
  • You expect to add new types of objects in the future without changing existing code.

For example, in a game, you might use a factory to create different types of enemies based on the level. Or in a document editor, a factory can create different types of documents like text, spreadsheet, or presentation.

Key Points

  • The Factory Pattern hides object creation details from the client.
  • It provides a common interface to create objects of different types.
  • It helps keep code flexible and easy to extend.
  • It reduces tight coupling between object users and object creators.

Key Takeaways

Factory Pattern separates object creation from usage to improve flexibility.
It allows creating objects based on input without changing client code.
Use it when you want to add new object types easily without modifying existing code.
It reduces dependencies between classes and promotes cleaner design.