Course contentsShow
← Software Engineering
Lesson 241 of 1,9337. Creational Design PatternsFree lesson

Simple Factory Pattern

Encapsulate object creation logic in a single factory class without inheritance hierarchy.

Simple Factory Pattern

What You'll Learn

You'll learn how to centralize object creation logic in one place without needing complex inheritance hierarchies.

The Core Idea

The Simple Factory Pattern is the most basic form of factory pattern. Instead of scattering new statements throughout your codebase, you create a single dedicated class (or method) responsible for deciding which concrete object to instantiate and return. It's simpler than Factory Method or Abstract Factory because it doesn't require inheritance or multiple factory implementations—just one class doing all the creation work.

Think of it like a pizza shop with one counter. You tell the counter what kind of pizza you want ("pepperoni," "veggie," "cheese"), and they hand you the right pizza. You don't need to know how each pizza is made or which oven was used—you just get your pizza from one place.

How It Works

A Simple Factory typically has:

  • A factory class with a creation method (often static)
  • Parameters passed to that method to determine which object to create
  • Conditional logic (like if or switch) inside the factory to decide which concrete class to instantiate
  • A common interface or base class for the objects being created

The client code calls the factory instead of using new directly. This encapsulates the instantiation logic, making it easier to change which classes get created without touching client code.

Benefits

  • Centralizes object creation in one location
  • Clients don't need to know concrete class names
  • Easy to add new product types (just update the factory)
  • Follows the DRY principle by avoiding repeated instantiation logic

Key Takeaway: The Simple Factory Pattern encapsulates object creation decisions in a single place, making your code cleaner and easier to modify without requiring inheritance hierarchies.