Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Count the classes (20 minutes)
List the subclasses needed for a room with projector, catering and recording, using inheritance for every combination. Then count the classes in the decorator design.
Done when: you have two counts (eight against four, plus the base).
Hint
Three extras give eight subsets, including none.
Easy 2: Run the stack (20 minutes)
Type the booking code and print the description and cost after each wrap.
Done when: you print 1000, 1550 and 1395 with the matching text.
Hint
Each Extra calls inner.cost() first.
Easy 3: Order matters (20 minutes)
Apply the discount before catering instead of after. Compare the totals.
Done when: you show two different totals and say which is fairer.
Hint
A 10 percent discount on a larger base removes more money.
Medium
Medium 1: Coffee shop (45 minutes)
Write Drink with Espresso and Latte, and decorators Milk, Caramel and ExtraShot, each with a price and a description.
Done when: a latte with caramel and two shots prints the right text and total.
Hint
The drink interface needs cost() and describe().
Medium 2: Timing decorator (45 minutes)
Write a TimedRepo that records how long save took, using an injected clock. Stack it with LoggingRepo.
Done when: a test with a fake clock sees both a log entry and a timing value.
Hint
Take the time before and after calling inner.save.
Medium 3: Stream decorators (45 minutes)
Write an UpperCaseReader that wraps a Reader and turns every character to upper case. Use it inside a BufferedReader.
Done when: reading "hello" through the stack gives "HELLO".
Hint
Override read(char[], int, int) in the wrapper.
Hard
Hard 1: Retry decorator (90 minutes)
Write a RetryingRepo that tries again up to three times when save throws. Test with a repo that fails twice and then works.
Done when: a test shows three calls and a final success, and a repo that always fails throws after three.
Hint
A loop with a counter and a catch.
Hard 2: Remove a decorator (90 minutes)
Build a way to turn a stack of decorators back into its parts, for example by giving each decorator an unwrap() method. Discuss why GoF warns about object identity.
Done when: you can list the layers of a stack, and a note explains the identity problem.
Hint
Identity changes because the wrapper is a different object.
Hard 3: Decorator or strategy (90 minutes)
A report needs optional header, footer and watermark, and a choice of format. Decide which parts are decorators and which are a strategy. Defend in a short design note.
Done when: a diagram and a note of under 200 words name each choice with a reason.
Hint
The format changes the algorithm, the extras add to the output.