# Decorator: Same Phone, More Features

SkyCast is slow and counts every call, so the hub needs today's weather remembered and every ask logged; subclasses for each combination (cached, logged, cached and logged) multiply with every feature, while decorators wrap the weather source in small layers that keep its interface, so features stack in any order without changing SkyCast.

Journeyman · OOP · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Add a feature to an object by wrapping it in another object that keeps the same interface
- Spot the smells that point to Decorator: a subclass for every combination of features
- Read an object diagram of wrapped objects, and say the order a call passes through them

## Key takeaways

- The smell: a subclass for every combination of features (CachedSkyCast, LoggedSkyCast, LoggedCachedSkyCast), each copying the others.
- The cause: features are welded on by inheritance, so each combination is a class of its own.
- The fix: each feature is a small object that keeps the same interface, holds another one and passes the call on, adding its bit before or after.
- Layers stack in any order, and the order matters: a log outside the cache records every ask; a log inside it records only the real calls.

**Before this:** *Proxy*, which met the hub's SkyCast client, and *Prefer Composition to Inheritance* (has-a instead of is-a). This lesson uses an object diagram, from *Object Diagrams: A Snapshot of Real Objects*.

The wall panel now shows today's weather, and so does the phone app, both from **SkyCast**, through the hub's SkyCast client. SkyCast is far away: each call takes about two seconds, and SkyCast counts every one. Maya asked for two things. Ask SkyCast once and remember the answer, so the second screen doesn't wait (that's a **cache**, a store of answers already worked out). And write every ask in the log, so she can see how often the hub asks. By the end of this lesson you'll have met the pattern for adding features like these, called *Decorator*.

## The symptom: a class for every combination

The team added the two features the way many people first reach for: subclasses of the SkyCast client. One remembers, one logs, and because the hub needs both, a third does both:

```csharp
IWeatherSource weather = new LoggedCachedSkyCast();
Console.WriteLine("Wall panel: " + weather.Today());
Console.WriteLine("Phone app: " + weather.Today());

interface IWeatherSource { string Today(); }

// The hub's SkyCast client: slow, and SkyCast counts every call.
class SkyCast : IWeatherSource
{
    public virtual string Today()
    {
        Console.WriteLine("SkyCast: asked over the internet (about 2 seconds)");
        return "72F, sunny";
    }
}

class CachedSkyCast : SkyCast
{
    private string? saved;
    public override string Today() => saved ??= base.Today();
}

class LoggedSkyCast : SkyCast
{
    public override string Today()
    {
        Console.WriteLine("Log: asking for today's weather");
        return base.Today();
    }
}

// Both features: the caching is copied from CachedSkyCast, the logging from LoggedSkyCast.
class LoggedCachedSkyCast : SkyCast
{
    private string? saved;
    public override string Today()
    {
        Console.WriteLine("Log: asking for today's weather");
        return saved ??= base.Today();
    }
}
```

```text
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
```

```java
interface WeatherSource { String today(); }

// The hub's SkyCast client: slow, and SkyCast counts every call.
class SkyCast implements WeatherSource {
    public String today() {
        IO.println("SkyCast: asked over the internet (about 2 seconds)");
        return "72F, sunny";
    }
}

class CachedSkyCast extends SkyCast {
    private String saved;
    public String today() {
        if (saved == null) saved = super.today();
        return saved;
    }
}

class LoggedSkyCast extends SkyCast {
    public String today() {
        IO.println("Log: asking for today's weather");
        return super.today();
    }
}

// Both features: the caching is copied from CachedSkyCast, the logging from LoggedSkyCast.
class LoggedCachedSkyCast extends SkyCast {
    private String saved;
    public String today() {
        IO.println("Log: asking for today's weather");
        if (saved == null) saved = super.today();
        return saved;
    }
}

void main() {
    WeatherSource weather = new LoggedCachedSkyCast();
    IO.println("Wall panel: " + weather.today());
    IO.println("Phone app: " + weather.today());
}
```

```text
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
```

```python
class SkyCast:
    """The hub's SkyCast client: slow, and SkyCast counts every call."""

    def today(self):
        print("SkyCast: asked over the internet (about 2 seconds)")
        return "72F, sunny"


class CachedSkyCast(SkyCast):
    def __init__(self):
        self.saved = None

    def today(self):
        if self.saved is None:
            self.saved = super().today()
        return self.saved


class LoggedSkyCast(SkyCast):
    def today(self):
        print("Log: asking for today's weather")
        return super().today()


class LoggedCachedSkyCast(SkyCast):
    """Both features: the caching is copied from CachedSkyCast, the logging from LoggedSkyCast."""

    def __init__(self):
        self.saved = None

    def today(self):
        print("Log: asking for today's weather")
        if self.saved is None:
            self.saved = super().today()
        return self.saved


weather = LoggedCachedSkyCast()
print("Wall panel: " + weather.today())
print("Phone app: " + weather.today())
```

```text
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
```

```javascript
// The hub's SkyCast client: slow, and SkyCast counts every call.
class SkyCast {
  today() {
    console.log("SkyCast: asked over the internet (about 2 seconds)");
    return "72F, sunny";
  }
}

class CachedSkyCast extends SkyCast {
  #saved = null;
  today() {
    this.#saved ??= super.today();
    return this.#saved;
  }
}

class LoggedSkyCast extends SkyCast {
  today() {
    console.log("Log: asking for today's weather");
    return super.today();
  }
}

// Both features: the caching is copied from CachedSkyCast, the logging from LoggedSkyCast.
class LoggedCachedSkyCast extends SkyCast {
  #saved = null;
  today() {
    console.log("Log: asking for today's weather");
    this.#saved ??= super.today();
    return this.#saved;
  }
}

const weather = new LoggedCachedSkyCast();
console.log("Wall panel: " + weather.today());
console.log("Phone app: " + weather.today());
```

```text
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
```

```typescript
interface WeatherSource { today(): string; }

// The hub's SkyCast client: slow, and SkyCast counts every call.
class SkyCast implements WeatherSource {
  today(): string {
    console.log("SkyCast: asked over the internet (about 2 seconds)");
    return "72F, sunny";
  }
}

class CachedSkyCast extends SkyCast {
  private saved: string | null = null;
  today(): string {
    this.saved ??= super.today();
    return this.saved;
  }
}

class LoggedSkyCast extends SkyCast {
  today(): string {
    console.log("Log: asking for today's weather");
    return super.today();
  }
}

// Both features: the caching is copied from CachedSkyCast, the logging from LoggedSkyCast.
class LoggedCachedSkyCast extends SkyCast {
  private saved: string | null = null;
  today(): string {
    console.log("Log: asking for today's weather");
    this.saved ??= super.today();
    return this.saved;
  }
}

const weather: WeatherSource = new LoggedCachedSkyCast();
console.log("Wall panel: " + weather.today());
console.log("Phone app: " + weather.today());
```

```text
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
```

It does what Maya asked: two asks are logged, and SkyCast is called once. But look at what it took. Three classes for two features, and the third is the other two copied together. Then the next request: count SkyCast's calls for the monthly bill. Counting alone, counting with caching, counting with logging, and all three: four more classes, seven in all. Every feature doubles the count.

And they're all welded to SkyCast. When HomeBase adds a backup weather service for the days SkyCast is down, none of these features work with it, unless all seven are copied again.

- **The symptom:** a subclass for every combination of features, each copying parts of the others.
- **The cause:** each feature is welded on by inheritance, so a combination can only exist as a class of its own, and only on top of one particular class.

## What would you try?

**Flags in the SkyCast client: `useCache`, `writeLog`, `countCalls`.** One class, three `if`s. But the client's job was talking to SkyCast, and now it does four jobs, and every new feature edits the code that talks to the network.

**Do the caching and logging in each screen.** The wall panel remembers its answer, the phone app remembers its own. That's two caches that don't know about each other, and two calls to SkyCast, and every new screen copies both.

**A helper function, `todayWithFeatures(cache, log)`.** The combinations move into one function's `if`s. It still has to change for every new feature.

What we want is for each feature to be its own small piece, written once, that can sit in front of *any* weather source, including another feature.

## The fix: wrap it, and it's still a phone

Put a phone in a case and it's still a phone: it rings, it takes pictures. Add a card wallet to the back, and a ring stand on that, and it's still a phone, with a few more things it can do. Each layer goes around the last one, and you can take any of them off.

![A phone in layers, seen from the back and side: the phone itself, a case around it, a card wallet stuck to the case and a ring stand on the wallet, each labeled. Each layer adds a feature, and the screen on the front still shows an incoming call: it's still a phone](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/0622f28fb23d4e4e97307b2f7cce5466.webp)

In code, each layer is a **decorator**: a small class that keeps the same interface as the thing it wraps, holds one of them, and passes each call on, adding its own bit before or after. `CachedWeather` is a `WeatherSource` that holds a `WeatherSource`; so is `LoggedWeather`. Because each one takes *any* weather source, they wrap each other:

![Decorator's roles: the wall panel asks today() of a feature layer, which keeps the WeatherSource promise, adds its bit before or after, and passes the call on to the next layer or the weather source. The layers, remember the answer and write it in the log, are fenced: which features, in which order](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/719f2b908ff94cfba4a5f4c8a9785559.webp)

```csharp
IWeatherSource weather = new LoggedWeather(new CachedWeather(new SkyCast()));
Console.WriteLine("Wall panel: " + weather.Today());
Console.WriteLine("Phone app: " + weather.Today());

interface IWeatherSource { string Today(); }

// The hub's SkyCast client, unchanged and on its own.
class SkyCast : IWeatherSource
{
    public string Today()
    {
        Console.WriteLine("SkyCast: asked over the internet (about 2 seconds)");
        return "72F, sunny";
    }
}

// A feature layer: a weather source that holds a weather source, and remembers its answer.
class CachedWeather : IWeatherSource
{
    private readonly IWeatherSource inner;
    private string? saved;
    public CachedWeather(IWeatherSource inner) { this.inner = inner; }
    public string Today() => saved ??= inner.Today();
}

// Another layer: writes every ask in the log, then passes it on.
class LoggedWeather : IWeatherSource
{
    private readonly IWeatherSource inner;
    public LoggedWeather(IWeatherSource inner) { this.inner = inner; }
    public string Today()
    {
        Console.WriteLine("Log: asking for today's weather");
        return inner.Today();
    }
}
```

```text
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
```

```java
interface WeatherSource { String today(); }

// The hub's SkyCast client, unchanged and on its own.
class SkyCast implements WeatherSource {
    public String today() {
        IO.println("SkyCast: asked over the internet (about 2 seconds)");
        return "72F, sunny";
    }
}

// A feature layer: a weather source that holds a weather source, and remembers its answer.
class CachedWeather implements WeatherSource {
    private final WeatherSource inner;
    private String saved;
    CachedWeather(WeatherSource inner) { this.inner = inner; }
    public String today() {
        if (saved == null) saved = inner.today();
        return saved;
    }
}

// Another layer: writes every ask in the log, then passes it on.
class LoggedWeather implements WeatherSource {
    private final WeatherSource inner;
    LoggedWeather(WeatherSource inner) { this.inner = inner; }
    public String today() {
        IO.println("Log: asking for today's weather");
        return inner.today();
    }
}

void main() {
    WeatherSource weather = new LoggedWeather(new CachedWeather(new SkyCast()));
    IO.println("Wall panel: " + weather.today());
    IO.println("Phone app: " + weather.today());
}
```

```text
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
```

```python
class SkyCast:
    """The hub's SkyCast client, unchanged and on its own."""

    def today(self):
        print("SkyCast: asked over the internet (about 2 seconds)")
        return "72F, sunny"


class CachedWeather:
    """A feature layer: a weather source that holds a weather source, and remembers its answer."""

    def __init__(self, inner):
        self.inner = inner
        self.saved = None

    def today(self):
        if self.saved is None:
            self.saved = self.inner.today()
        return self.saved


class LoggedWeather:
    """Another layer: writes every ask in the log, then passes it on."""

    def __init__(self, inner):
        self.inner = inner

    def today(self):
        print("Log: asking for today's weather")
        return self.inner.today()


weather = LoggedWeather(CachedWeather(SkyCast()))
print("Wall panel: " + weather.today())
print("Phone app: " + weather.today())
```

```text
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
```

```javascript
// The hub's SkyCast client, unchanged and on its own.
class SkyCast {
  today() {
    console.log("SkyCast: asked over the internet (about 2 seconds)");
    return "72F, sunny";
  }
}

// A feature layer: a weather source that holds a weather source, and remembers its answer.
class CachedWeather {
  #inner;
  #saved = null;
  constructor(inner) { this.#inner = inner; }
  today() {
    this.#saved ??= this.#inner.today();
    return this.#saved;
  }
}

// Another layer: writes every ask in the log, then passes it on.
class LoggedWeather {
  #inner;
  constructor(inner) { this.#inner = inner; }
  today() {
    console.log("Log: asking for today's weather");
    return this.#inner.today();
  }
}

const weather = new LoggedWeather(new CachedWeather(new SkyCast()));
console.log("Wall panel: " + weather.today());
console.log("Phone app: " + weather.today());
```

```text
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
```

```typescript
interface WeatherSource { today(): string; }

// The hub's SkyCast client, unchanged and on its own.
class SkyCast implements WeatherSource {
  today(): string {
    console.log("SkyCast: asked over the internet (about 2 seconds)");
    return "72F, sunny";
  }
}

// A feature layer: a weather source that holds a weather source, and remembers its answer.
class CachedWeather implements WeatherSource {
  private readonly inner: WeatherSource;
  private saved: string | null = null;
  constructor(inner: WeatherSource) { this.inner = inner; }
  today(): string {
    this.saved ??= this.inner.today();
    return this.saved;
  }
}

// Another layer: writes every ask in the log, then passes it on.
class LoggedWeather implements WeatherSource {
  private readonly inner: WeatherSource;
  constructor(inner: WeatherSource) { this.inner = inner; }
  today(): string {
    console.log("Log: asking for today's weather");
    return this.inner.today();
  }
}

const weather: WeatherSource = new LoggedWeather(new CachedWeather(new SkyCast()));
console.log("Wall panel: " + weather.today());
console.log("Phone app: " + weather.today());
```

```text
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
```

The same five lines, from two small layers instead of three welded classes. Counting calls for the bill is one more layer, and it combines with the others for free: `new CountedWeather(new LoggedWeather(new CachedWeather(new SkyCast())))`. The backup weather service gets every feature by being wrapped the same way. And `SkyCast` went back to doing one job: talking to SkyCast.

`??=` in C#, JavaScript and TypeScript means "if this is still empty, set it to…", so `saved ??= inner.Today()` asks the inner source only the first time. Python and Java write the same thing as an `if`.

## Reading the layers

A class diagram shows that `LoggedWeather` and `CachedWeather` each *have a* `WeatherSource`, but not how many layers there are at run time, or in what order. An **object diagram** does: a snapshot of the real objects, each box named `object : Class`, with arrows for what each one holds.

![The hub's weather at run time, one object inside the next: the wall panel asks LoggedWeather for today(); it logs the ask and asks CachedWeather, which remembers the answer "72F, sunny" and asks SkyCast only the first time](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/0c362cd5d5af49c3804bbdf001c0871d.webp)

A call goes in at the outside and passes inward, one layer at a time: the log writes its line, the cache answers if it can, and only an empty cache passes the call on to SkyCast. The answer comes back out the same way.

So **the order matters.** Here the log is outside the cache, so it records every ask, both screens'. Swap them, `new CachedWeather(new LoggedWeather(new SkyCast()))`, and the cache answers the second ask before it reaches the log: the log records only the real calls to SkyCast. Both are useful; they answer different questions ("how often does the hub ask?" against "how often do we pay?").

**Try it.** Swap the two layers in your language's tab and run it again. The second `Log:` line disappears.

A real cache also forgets after a while, since tomorrow's weather isn't today's; ten minutes is a common choice. This one keeps its answer for the life of the program, to keep the idea plain.

## How it got its name

Teams kept adding features to objects this way, layer around layer, so the 1994 book named it after what you do to a cake or a room: you *decorate* it, adding to it without changing what it is. It's the **Decorator pattern**, also called a *wrapper*. The object at the center is the *component*; each layer is a *decorator*. It's Module 1's two big ideas at once: *prefer composition to inheritance* (each layer *has a* source), and the **open/closed principle** (a new feature is a new class; `SkyCast` is never edited).

The next lesson shows the modern version: the same layers, as functions that wrap functions.

## Where you've already used it

- Java's `new BufferedReader(new FileReader("rooms.txt"))`: a file reader, wrapped in a layer that reads in big chunks, and still a `Reader`.
- C#'s `new GZipStream(fileStream, CompressionMode.Compress)`: a stream, wrapped in a layer that squeezes what's written to it, and still a `Stream`.
- Python's `@functools.cache` above a function, which you'll meet properly in the next lesson.
- The middleware in web frameworks (ASP.NET Core, Express), which wraps every request in layers: Pass 4 has a lesson on it.

## When not to use it

- **When there's one feature and one combination.** If the weather only ever needs a cache, one `CachedWeather` is enough; it's still a decorator, but there's no stack to plan.
- **When the interface is big.** A decorator must pass on *every* method of what it wraps. Wrapping an interface with twenty methods to change one is a lot of passing on; consider a smaller interface first.
- **When the order is hard to see.** Five layers built in five different files make "why was that logged twice?" hard to answer. Build the stack in one place, where it can be read top to bottom.

The cost is one small class per feature, and a call that passes through several objects on its way in.

**How often you'll meet it:** every day (our estimate: you'll use decorators in every language's file and stream classes, and write them whenever a feature has to be added in front of something you don't want to change).

## Check yourself

2 questions to try on the lesson page.

## So what

When features start multiplying as subclasses, stop welding them on. Make each feature a thin layer that keeps the same interface, and stack the layers you need, in the order you mean.

## Key terms

- [Decorator Pattern](https://www.ask-codey.com/glossary/decorator-pattern)
- [Cache](https://www.ask-codey.com/glossary/cache-software-development)
- [Composition](https://www.ask-codey.com/glossary/composition-oop)
- [Open/Closed Principle](https://www.ask-codey.com/glossary/open-closed-principle)

## Cheat sheets

- [Decorator: Same Phone, More Features](https://www.ask-codey.com/cheat-sheets/dp-decorator-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-decorator
