Factory Pattern: What It Is and How It Works
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.
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()
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.