Decorator
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:
BufferedReaderwrapping aReader.
Draft outline details
Demonstration
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.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.