Skip to main content

Decorator

StructuralGang of FourEnhancementExtensibilityWrappingAbout 3 min

Also known as

  • Smart Proxy
  • Wrapper

Intent

The Decorator pattern allows for the dynamic addition of responsibilities to objects without modifying their existing code. It achieves this by providing a way to "wrap" objects within objects of similar interface.

Explanation

Real-world example

There is an angry troll living in the nearby hills. Usually, it goes bare-handed, but sometimes it has a weapon. To arm the troll it's not necessary to create a new troll but to decorate it dynamically with a suitable weapon.

In plain words

Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class.

Wikipedia says

In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern as well as to the Open-Closed Principle, by allowing the functionality of a class to be extended without being modified.

Programmatic Example

Let's take the troll example. First of all we have a SimpleTroll implementing the Troll interface:

public interface Troll {
    void attack();

    int getAttackPower();

    void fleeBattle();
}

@Slf4j
public class SimpleTroll implements Troll {

    @Override
    public void attack() {
        LOGGER.info("The troll tries to grab you!");
    }

    @Override
    public int getAttackPower() {
        return 10;
    }

    @Override
    public void fleeBattle() {
        LOGGER.info("The troll shrieks in horror and runs away!");
    }
}

Next, we want to add a club for the troll. We can do it dynamically by using a decorator:


@Slf4j
public class ClubbedTroll implements Troll {

    private final Troll decorated;

    public ClubbedTroll(Troll decorated) {
        this.decorated = decorated;
    }

    @Override
    public void attack() {
        decorated.attack();
        LOGGER.info("The troll swings at you with a club!");
    }

    @Override
    public int getAttackPower() {
        return decorated.getAttackPower() + 10;
    }

    @Override
    public void fleeBattle() {
        decorated.fleeBattle();
    }
}

Here's the troll in action:

// simple troll
LOGGER.info("A simple looking troll approaches.");
var troll=new SimpleTroll();
troll.attack();
troll.fleeBattle();
LOGGER.info("Simple troll power: {}.\n",troll.getAttackPower());

// change the behavior of the simple troll by adding a decorator
LOGGER.info("A troll with huge club surprises you.");
var clubbedTroll=new ClubbedTroll(troll);
clubbedTroll.attack();
clubbedTroll.fleeBattle();
LOGGER.info("Clubbed troll power: {}.\n",clubbedTroll.getAttackPower());

Program output:

A simple looking troll approaches.
The troll tries to grab you!
The troll shrieks in horror and runs away!
Simple troll power:10.

A troll with huge club surprises you.
The troll tries to grab you!
The troll swings at you with a club!
The troll shrieks in horror and runs away!
Clubbed troll power:20.

Class diagram

alt text
Decorator pattern class diagram

Applicability

Decorator is used to:

  • Add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
  • For responsibilities that can be withdrawn.
  • When extending a class is impractical due to the proliferation of subclasses that could result.
  • For when a class definition might be hidden or otherwise unavailable for subclassing.

Tutorials

Known uses

Consequences

Benefits:

  • Greater flexibility than static inheritance.
  • Avoids feature-laden classes high up in the hierarchy.
  • A decorator and its component aren't identical.
  • Responsibilities can be added or removed at runtime.

Trade-offs:

  • A decorator and its component aren't identical, so tests for object type will fail.
  • Decorators can lead to a system with lots of small objects that look alike to the programmer, making the desired configuration hard to achieve.
  • Overuse can complicate the code structure due to the introduction of numerous small classes.
  • Adapteropen in new window: A decorator changes an object's responsibilities, while an adapter changes an object's interface.
  • Compositeopen in new window: Decorators can be viewed as a degenerate composite with only one component. However, a decorator adds additional responsibilities—it isn't intended for object aggregation.
  • Strategyopen in new window: Decorator lets you change the skin of an object, while Strategy lets you change the guts.

Credits