Glossary

Decorator Pattern

Decorator is a pattern that dynamically adds new functionality to an object without changing its class. It wraps the original object and extends or alters its behaviour while implementing the same interface.

Example

interface Logger { log(string $msg): void; }

class FileLogger implements Logger { ... }

class TimestampLogger implements Logger {
  public function __construct(private Logger $inner) {}
  public function log(string $msg): void {
    $this->inner->log(date('H:i:s') . ' ' . $msg);
  }
}

Advantages over inheritance

Decorators compose dynamically: new JsonLogger(new TimestampLogger(new FileLogger())). Inheritance would require N² subclasses for every combination. Decorators avoid the Open/Closed violation that inheritance frequently causes.