Structural Design Pattern

Decorator Design Pattern in Java

Add responsibilities to an object dynamically without changing its original class.

In this lesson: Decorator wraps an object that implements the same interface and adds behavior before or after delegating to the wrapped object.

Overview

Decorator is useful when its recurring design problem appears in a real application. It keeps the relevant responsibilities organized while allowing surrounding code to depend on clear abstractions.

Implementation

interface Message { String text(); }
final class PlainMessage implements Message { public String text() { return "Hello"; } }
final class EncryptedMessage implements Message { private final Message message; EncryptedMessage(Message message) { this.message = message; } public String text() { return "[encrypted] " + message.text(); } }
Message message = new EncryptedMessage(new PlainMessage());
System.out.println(message.text());

When should you use it?

Use Decorator when behavior should be added in combinations at runtime without creating a large inheritance hierarchy.

Next step: Continue with the Design Patterns course and explore the next pattern.