# Design patterns: Decorator

> The Decorator design pattern with examples in PHP

- URL: https://mautoblog.com/en/posts/design-patterns/decorator/
- Language: en
- Published: 2024-09-27
- Updated: 2026-10-14
- Author: Mauto
- Categories: Software Development, Technology
- Tags: Software Architecture, Best Practices, PHP
- Guide: Design Patterns (part 10)
- Translation (it): https://mautoblog.com/posts/design-patterns/decorator/

---
The Decorator pattern is a structural design pattern that lets you add behavior to an object dynamically.

## Characteristics of the Decorator pattern
1. **Dynamic addition of behavior:** The Decorator Pattern lets you add new behaviors and responsibilities to existing objects dynamically, without altering the original code.
2. **Flexible composition:** It lets you combine different decorators to extend an object's functionality, offering great flexibility when building complex behaviors.
3. **Follows the Open/Closed Principle:** It follows the open/closed principle, letting you extend the functionality of objects without modifying existing code. You can add decorators without changing the original classes.
4. **Support for complex objects:** It makes it easy to manage objects with many variations and options, letting you create complex configurations without needing a static class hierarchy.
5. **Unified interface:** Decorated objects and original objects implement the same interface, so clients can use decorated and undecorated objects interchangeably, without worrying about implementation differences.

### Example in PHP:

```php
interface Coffee {
    public function cost();
}

class BasicCoffee implements Coffee {
    public function cost() {
        return 5;
    }
}

class MilkDecorator implements Coffee {
    private $coffee;

    public function __construct(Coffee $coffee) {
        $this->coffee = $coffee;
    }

    public function cost() {
        return $this->coffee->cost() + 2; // Adds the cost of the milk
    }
}

class SugarDecorator implements Coffee {
    private $coffee;

    public function __construct(Coffee $coffee) {
        $this->coffee = $coffee;
    }

    public function cost() {
        return $this->coffee->cost() + 1; // Adds the cost of the sugar
    }
}

// Usage
$basicCoffee = new BasicCoffee();
$milkCoffee = new MilkDecorator($basicCoffee);

echo $milkCoffee->cost() . "\n"; // 7 (5 + 2)

// Decorators can be combined: milk and sugar
$milkSugarCoffee = new SugarDecorator(new MilkDecorator(new BasicCoffee()));

echo $milkSugarCoffee->cost() . "\n"; // 8 (5 + 2 + 1)
```

[BACK TO THE GUIDE](/en/posts/design-patterns/)

