Skip to content
Ameen Abozaid
In reviewJNR-005-L06

Decorator

  • Lesson 6 of 10
  • 11 min read
  • Junior
On This Lesson 4 topics

The content for this lesson is written and waiting for review. The outline below shows what it covers. It will be published once it is approved.

In this lesson

add behavior by wrapping an object.

Planned topics

  • Problem: add logging or caching without changing the original class.
  • A decorator implements the same interface and holds another one inside.
  • It adds its work, then calls the inner one.
  • Decorators can be stacked.
  • JDK example: BufferedReader wrapping a Reader.
Draft outline details

Demonstration

java
class CachedPriceLookup implements PriceLookup {
    private final PriceLookup inner;
    private final Map<Sku, Money> cache = new HashMap<>();
    public Money priceOf(Sku s) { return cache.computeIfAbsent(s, inner::priceOf); }
}

Check your understanding

What must a decorator share with the object it wraps?

Show answer

The same interface.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.