Python Design Patterns

Factory Method Pattern in Python

Factory Method separates object construction from the code that uses the resulting interface.

What is Factory Method Pattern?

Factory Method separates object construction from the code that uses the resulting interface.

Let subclasses or a factory method choose which concrete object to create.

When should you use it?

  • Solve recurring object-design problems with proven structures.
  • Decouple responsibilities so code is easier to extend and test.
  • Use shared design vocabulary when discussing architecture with a team.

Example code

Run code →
main.py
class EmailNotification:
    # Factory Method: creation is separated from object usage.
    def send(self, message):
        return f"Email: {message}"


class SmsNotification:
    def send(self, message):
        return f"SMS: {message}"


def create_notification(channel):
    # Centralize the concrete-class selection.
    factories = {"email": EmailNotification, "sms": SmsNotification}
    return factories[channel]()


notification = create_notification("email")
print(notification.send("Hello"))

Expected output

Email: Hello

How it works

The factory selects a notification class while the caller only depends on its send method.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Replace the sample domain while preserving the pattern structure.
  2. Compare the pattern with a simpler implementation and explain the tradeoff.
  3. Write tests for each participant before adding another implementation.
Run in Python IDE →