> 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/decorator-pattern.md).

# Decorator Pattern

The **Decorator Pattern** is a **structural design pattern** that allows you to dynamically add new behavior to an object without modifying its original class.

It follows the principle:

> “Composition over inheritance”

***

## Real Life Example

Think about a **Coffee Shop** ☕

You start with:

* Basic Coffee

Then you can add:

* Milk
* Sugar
* Chocolate

Instead of creating many subclasses like:

```
MilkCoffee
SugarCoffee
MilkSugarCoffee
ChocolateMilkCoffee
```

Decorator Pattern adds features dynamically.

***

## Structure

```
Component
 ├── Concrete Component
 └── Decorator
       └── Concrete Decorators
```

***

## Laravel / PHP Example

### Scenario

We are building a notification system.

Base notification:

* Simple message

Extra features:

* Email logging
* SMS logging
* Database logging

***

## Step 1: Component Interface

```
interface Notification
{
    public function send(): string;
}
```

***

## Step 2: Concrete Component

Basic notification.

```
class BasicNotification implements Notification
{
    public function send(): string
    {
        return "Sending notification";
    }
}
```

***

## Step 3: Base Decorator

```
abstract class NotificationDecorator implements Notification
{
    protected Notification $notification;

    public function __construct(Notification $notification)
    {
        $this->notification = $notification;
    }

    public function send(): string
    {
        return $this->notification->send();
    }
}
```

***

## Step 4: Concrete Decorators

### Email Decorator

```
class EmailDecorator extends NotificationDecorator
{
    public function send(): string
    {
        return $this->notification->send() . " + Email Sent";
    }
}
```

***

### SMS Decorator

```
class SmsDecorator extends NotificationDecorator
{
    public function send(): string
    {
        return $this->notification->send() . " + SMS Sent";
    }
}
```

***

### Database Log Decorator

```
class DatabaseLoggerDecorator extends NotificationDecorator
{
    public function send(): string
    {
        return $this->notification->send() . " + Logged to Database";
    }
}
```

***

## Step 5: Usage

### Basic Notification

```
$notification = new BasicNotification();

echo $notification->send();
```

#### Output

```
Sending notification
```

***

### Add Email Feature

```
$notification = new EmailDecorator(
    new BasicNotification()
);

echo $notification->send();
```

#### Output

```
Sending notification + Email Sent
```

***

### Add Multiple Features

```
$notification = new SmsDecorator(
    new EmailDecorator(
        new DatabaseLoggerDecorator(
            new BasicNotification()
        )
    )
);

echo $notification->send();
```

***

## Output

```
Sending notification + Logged to Database + Email Sent + SMS Sent
```

***

## How Decorator Works

Each decorator wraps another object.

```
BasicNotification
    ↓
DatabaseDecorator
    ↓
EmailDecorator
    ↓
SmsDecorator
```

Each layer adds new behavior.

***

## Advantages

### 1. Dynamic Behavior Addition

Add features at runtime.

***

### 2. Avoids Massive Inheritance

Without decorator:

```
EmailSmsNotification
EmailDatabaseNotification
SmsDatabaseNotification
```

Too many classes.

***

### 3. Follows Open/Closed Principle

Open for extension, closed for modification.

***

## Real Laravel Use Cases

| Use Case      | Example                     |
| ------------- | --------------------------- |
| Middleware    | Request decoration          |
| Logging       | Add logging dynamically     |
| Cache         | Cache wrapper               |
| Notifications | Multi-channel notifications |
| API Response  | Response formatting         |

***

## Decorator vs Composite

| Decorator            | Composite             |
| -------------------- | --------------------- |
| Adds behavior        | Builds tree structure |
| Wraps single object  | Manages child objects |
| Focus on enhancement | Focus on hierarchy    |

***

## Decorator vs Inheritance

| Decorator           | Inheritance                |
| ------------------- | -------------------------- |
| Runtime flexibility | Compile-time structure     |
| Composition based   | Class hierarchy            |
| More scalable       | Can create class explosion |

***

## When to Use Decorator Pattern

Use Decorator Pattern when:

✅ You want to add features dynamically\
✅ You want flexible object enhancement\
✅ You want to avoid subclass explosion\
✅ Features can be combined independently

***

## Short Interview Definition

> The Decorator Pattern dynamically adds new behavior to objects by wrapping them inside decorator classes without modifying the original object.
