For the complete documentation index, see llms.txt. This page is also available as Markdown.

Creational Design Patterns

Creational design patterns deal with object creation mechanisms – how objects are instantiated in a way that is flexible and reusable. They help make a system independent of how its objects are created, composed, and represented.

Here are the most popular creational design patterns with simple examples:


1. Singleton Pattern

Ensures that a class has only one instance and provides a global point of access to it.

✅ Use when you need only one instance (like DB connection, Logger, Config).

Example (PHP):

class Database {
    private static ?Database $instance = null;
    private function __construct() {
        echo "DB Connection Created\n";
    }

    public static function getInstance(): Database {
        if (self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance;
    }
}

// Usage
$db1 = Database::getInstance();
$db2 = Database::getInstance();

var_dump($db1 === $db2); // true

2. Factory Method Pattern

Defines an interface for creating an object but lets subclasses alter the type of objects that will be created.

✅ Use when the exact object type isn’t known until runtime.

Example (PHP):


3. Abstract Factory Pattern

Provides an interface for creating families of related objects without specifying their concrete classes.

✅ Use when you want to create related products together.

Example (PHP):


4. Builder Pattern

Separates the construction of a complex object from its representation.

✅ Use when creating complex objects step by step.

Example (PHP):


5. Prototype Pattern

Creates new objects by cloning an existing object (instead of creating from scratch).

✅ Use when creating an object is costly or complex.

Example (PHP):


🔑 Summary of Creational Patterns:

  1. Singleton → One instance only.

  2. Factory Method → Create object via a method.

  3. Abstract Factory → Create families of related objects.

  4. Builder → Step-by-step complex object creation.

  5. Prototype → Clone existing objects.

Last updated