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

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


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


Step 2: Concrete Component

Basic notification.


Step 3: Base Decorator


Step 4: Concrete Decorators

Email Decorator


SMS Decorator


Database Log Decorator


Step 5: Usage

Basic Notification

Output


Add Email Feature

Output


Add Multiple Features


Output


How Decorator Works

Each decorator wraps another object.

Each layer adds new behavior.


Advantages

1. Dynamic Behavior Addition

Add features at runtime.


2. Avoids Massive Inheritance

Without decorator:

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.

Last updated