> For the complete documentation index, see [llms.txt](https://al-mamun.gitbook.io/al-mamun/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://al-mamun.gitbook.io/al-mamun/design-patterns/creational-design-patterns.md).

# 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):**

```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):**

```php
interface Product {
    public function getName(): string;
}

class Book implements Product {
    public function getName(): string {
        return "Book";
    }
}

class Pen implements Product {
    public function getName(): string {
        return "Pen";
    }
}

class ProductFactory {
    public static function create(string $type): Product {
        return match($type) {
            'book' => new Book(),
            'pen' => new Pen(),
            default => throw new Exception("Unknown product"),
        };
    }
}

// Usage
$product = ProductFactory::create('book');
echo $product->getName(); // Book
```

***

### 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):**

```php
// Abstract product interfaces
interface Button { public function render(): string; }
interface Checkbox { public function check(): string; }

// Concrete products
class WinButton implements Button { public function render(): string { return "Windows Button"; } }
class WinCheckbox implements Checkbox { public function check(): string { return "Windows Checkbox"; } }

class MacButton implements Button { public function render(): string { return "Mac Button"; } }
class MacCheckbox implements Checkbox { public function check(): string { return "Mac Checkbox"; } }

// Abstract Factory
interface GUIFactory {
    public function createButton(): Button;
    public function createCheckbox(): Checkbox;
}

// Concrete Factories
class WinFactory implements GUIFactory {
    public function createButton(): Button { return new WinButton(); }
    public function createCheckbox(): Checkbox { return new WinCheckbox(); }
}
class MacFactory implements GUIFactory {
    public function createButton(): Button { return new MacButton(); }
    public function createCheckbox(): Checkbox { return new MacCheckbox(); }
}

// Usage
function buildUI(GUIFactory $factory) {
    $button = $factory->createButton();
    $checkbox = $factory->createCheckbox();
    echo $button->render() . " & " . $checkbox->check();
}

buildUI(new MacFactory()); // Mac Button & Mac Checkbox
```

***

### 4. **Builder Pattern**

Separates the construction of a complex object from its representation.

✅ Use when creating complex objects step by step.

**Example (PHP):**

```php
class Car {
    public string $engine;
    public string $color;
    public string $seats;
}

class CarBuilder {
    private Car $car;
    public function __construct() { $this->car = new Car(); }
    public function setEngine(string $engine): self { $this->car->engine = $engine; return $this; }
    public function setColor(string $color): self { $this->car->color = $color; return $this; }
    public function setSeats(string $seats): self { $this->car->seats = $seats; return $this; }
    public function build(): Car { return $this->car; }
}

// Usage
$car = (new CarBuilder())->setEngine("V8")->setColor("Red")->setSeats("4")->build();
print_r($car);
```

***

### 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):**

```php
class Document {
    public string $title;
    public string $content;

    public function __clone() {
        // Custom clone logic (if needed)
    }
}

// Usage
$doc1 = new Document();
$doc1->title = "Original";
$doc1->content = "Hello World";

$doc2 = clone $doc1;
$doc2->title = "Copy";

print_r($doc1);
print_r($doc2);
```

***

#### 🔑 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.
