Pixel-art RPG character equipped with multiple power-ups illustrating the Decorator design pattern.

Welcome back to PHP Design Patterns Game! In our previous article, we explored the State Pattern by creating a character whose behavior changes depending on its current condition.

This time, we will approach a different problem: extending a character’s abilities without creating a new class for every possible combination of equipment and power-ups.

Imagine a role-playing game where a hero can equip a sword, wear armor, and receive a magical blessing.

Each item changes the character’s characteristics. The sword increases attack power, armor improves defense, and a magical blessing adds another bonus.

What happens when the player combines several items?

The Decorator Pattern allows us to extend an object’s behavior dynamically by wrapping it inside other objects implementing the same interface.

The Problem: Too Many Character Classes

A straightforward object-oriented implementation might begin with a Hero class.

When the hero acquires a sword, we could introduce a SwordHero subclass. When the hero wears armor, we might create an ArmoredHero subclass.

But what about a hero carrying a sword and wearing armor?

We could create SwordArmoredHero. Then perhaps SwordArmoredBlessedHero.

This approach quickly becomes difficult to maintain because each new equipment type introduces more possible combinations.

The problem is not inheritance itself. The problem is using inheritance to represent combinations of independently changing features.

Composition provides a more flexible alternative.

Understanding the Decorator Pattern

The Decorator Pattern consists of a common component interface, a concrete component, and decorators that implement the same interface while holding a reference to another component.

Each decorator delegates to the wrapped component and adds its own behavior.

In our game, the basic hero provides attack and defense values. Equipment decorators modify those values while preserving the same interface.

Because every decorator is also a character component, decorators can wrap other decorators.

This is what makes combinations possible without creating a separate class for every equipment configuration.

Building Our RPG Character

We will build a small command-line demonstration using PHP 8.2 or later.

Our hero begins with an attack value of 10 and a defense value of 5.

We will introduce three decorators:

  • Sword: Adds 7 attack points.
  • Armor: Adds 8 defense points.
  • Blessing: Adds 3 attack points and 2 defense points.

The goal is to equip these items in different combinations without modifying the Hero class.

Complete PHP Implementation

Save the following code as decorator-game.php.

<?php

declare(strict_types=1);

interface Character
{
    public function name(): string;
    public function attack(): int;
    public function defense(): int;
}

final class Hero implements Character
{
    public function name(): string
    {
        return 'Hero';
    }

    public function attack(): int
    {
        return 10;
    }

    public function defense(): int
    {
        return 5;
    }
}

abstract class Equipment implements Character
{
    public function __construct(
        protected Character $character
    ) {}

    public function name(): string
    {
        return $this->character->name();
    }

    public function attack(): int
    {
        return $this->character->attack();
    }

    public function defense(): int
    {
        return $this->character->defense();
    }
}

final class Sword extends Equipment
{
    public function name(): string
    {
        return parent::name() . ' + Sword';
    }

    public function attack(): int
    {
        return parent::attack() + 7;
    }
}

final class Armor extends Equipment
{
    public function name(): string
    {
        return parent::name() . ' + Armor';
    }

    public function defense(): int
    {
        return parent::defense() + 8;
    }
}

final class Blessing extends Equipment
{
    public function name(): string
    {
        return parent::name() . ' + Blessing';
    }

    public function attack(): int
    {
        return parent::attack() + 3;
    }

    public function defense(): int
    {
        return parent::defense() + 2;
    }
}

function showCharacter(Character $character): void
{
    printf(
        "%s | Attack: %d | Defense: %d\n",
        $character->name(),
        $character->attack(),
        $character->defense()
    );
}

$hero = new Hero();

showCharacter($hero);

$hero = new Sword($hero);
showCharacter($hero);

$hero = new Armor($hero);
showCharacter($hero);

$hero = new Blessing($hero);
showCharacter($hero);

// Verify the final equipment combination.
assert($hero->attack() === 20);
assert($hero->defense() === 15);

Running the Game

Execute the program from the command line:

php decorator-game.php

The expected output is:

Hero | Attack: 10 | Defense: 5
Hero + Sword | Attack: 17 | Defense: 5
Hero + Sword + Armor | Attack: 17 | Defense: 13
Hero + Sword + Armor + Blessing | Attack: 20 | Defense: 15

Notice that the original Hero class remains unchanged throughout the example.

Each item wraps the existing character and contributes its own modification.

The resulting object still implements Character, so the showCharacter() function does not need to know whether it receives a basic hero or a character equipped with several items.

How the Decorators Work Together

The final object is constructed through nested composition.

$hero = new Blessing(
    new Armor(
        new Sword(
            new Hero()
        )
    )
);

When attack() is called, the Blessing decorator delegates to Armor, which delegates to Sword, which delegates to Hero.

Each layer adds its contribution before returning the result.

The same process occurs when defense() is called, although different decorators modify different characteristics.

In this example, the bonuses are additive, so the order of the decorators does not change the final numerical values.

That is not always true. If decorators apply percentage multipliers, caps, or conditional effects, the order of wrapping can influence the result.

Decorator Versus Inheritance

Inheritance remains useful when objects share a stable relationship and subclasses represent meaningful specializations.

However, equipment is not necessarily a specialization of a character. It is an optional capability that can be added or removed.

The Decorator Pattern models that distinction directly.

Instead of defining a new character class for every combination, we assemble the required behavior from reusable components.

This makes the system easier to extend when new equipment types are introduced.

When Should You Avoid the Decorator Pattern?

The pattern is not automatically the best solution for every game inventory system.

If a character has only a few numeric attributes and equipment simply adds values, a collection of item modifiers may be simpler than a hierarchy of decorator objects.

Decorators become more attractive when equipment introduces distinct behavior, such as changing attack calculations, applying conditional effects, or altering how actions are processed.

Another limitation is removal. In our example, removing an item requires rebuilding the wrapper chain or introducing an explicit equipment-management mechanism.

Long decorator chains can also complicate debugging and object serialization.

As with other design patterns, the objective is to manage complexity rather than introduce it unnecessarily.

Your Turn: Add a Magical Ring

Let’s extend our game with a new item.

Create a Ring decorator that increases attack by 2 points and defense by 4 points.

Equip the ring after the sword, armor, and blessing. The final character should have 22 attack points and 19 defense points.

For an additional challenge, introduce a Berserker decorator that multiplies attack by 1.5 while reducing defense by 3 points.

Experiment with the order in which decorators are applied. Does changing the order affect the final result?

Finally, consider how you would implement equipment removal without modifying the Hero class.

Conclusion

The Decorator Pattern provides a flexible way to extend object behavior without creating a new subclass for every possible combination of features.

Our RPG example demonstrates how weapons, armor, and magical effects can be composed dynamically while preserving a common Character interface.

The same architectural approach can be applied beyond games, including HTTP middleware, logging, data transformation, and configurable processing pipelines.

In the next PHP Design Patterns Game article, we will explore the Command Pattern by building a small game that records player actions and supports undo and replay.

LEAVE A REPLY

Please enter your comment!
Please enter your name here