JavaOmnibus
GoF Decorator
GoF pattern • Structural
GoFStructuralJava example

Decorator solves a specific structural problem in the design.

Add behavior to an object dynamically without changing its core type.

Pattern overview

GoF pattern

Add behavior to an object dynamically without changing its core type.

Intent

Attach additional responsibilities to an object dynamically while preserving the same interface.

Problem

You need optional behavior combinations without creating a deep inheritance tree for every variant.

Solution

Wrap an object with decorator implementations that add behavior before or after delegating.

Fit and tradeoffs

FamilyGoF
CategoryStructural
Best used when
  • When features are optional and composable.
  • When you want to layer logging, caching, timing, or authorization.
Tradeoffs
  • Many wrappers can make debugging call flow harder.
  • Object identity and equality may need careful thought.

Java example

This example is intentionally compact so the pattern shape stays easy to see.

interface InventoryClient {
    int available(String sku);
}

final class HttpInventoryClient implements InventoryClient {
    public int available(String sku) { return 42; }
}

final class TimedInventoryClient implements InventoryClient {
    private final InventoryClient delegate;

    TimedInventoryClient(InventoryClient delegate) {
        this.delegate = delegate;
    }

    public int available(String sku) {
        long start = System.nanoTime();
        try {
            return delegate.available(sku);
        } finally {
            System.out.println("lookup took " + (System.nanoTime() - start));
        }
    }
}

Related pages

Keep exploring