Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Find the mismatch (20 minutes)
A weather library returns temperature in Fahrenheit as a string, such as "72F". Your code wants Celsius as a double. Write the target interface.
Done when: you have the interface and a list of the conversions the adapter must do.
Hint
The target hides the unit and the text format.
Easy 2: Run the adapter (20 minutes)
Type the VendorPayments code and run charge("asha", 500) and charge("asha", 0).
Done when: you print true and false.
Hint
The vendor method takes paise, not rupees.
Easy 3: Label the roles (20 minutes)
Label target, client, adaptee and adapter in the payment code.
Done when: four classes have four labels.
Hint
The vendor class is the adaptee.
Medium
Medium 1: Temperature adapter (45 minutes)
Write the weather adapter from Easy 1 and test it with "72F" and "32F".
Done when: you get about 22.2 and 0.0 Celsius.
Hint
Celsius is (F minus 32) times 5 over 9.
Medium 2: Two vendors (45 minutes)
Add a second vendor class with different method names. Write its adapter. Switch between the two through the Payments interface.
Done when: the client code is unchanged for both.
Hint
Each vendor gets its own adapter class.
Medium 3: Write the facade (45 minutes)
Type the facade with fakes for the four services. Test the success path, the busy path and the payment failure path.
Done when: three tests pass and the failure test shows that nothing is held or sent.
Hint
A fake notifier stores messages in a list.
Hard
Hard 1: Adapt a legacy list (90 minutes)
A legacy class exposes Enumeration<String>. Adapt it to Java's Iterator<String> and use it in a for-each loop through an Iterable.
Done when: a for-each prints every item of the legacy source.
Hint
hasMoreElements becomes hasNext.
Hard 2: Facade or not (90 minutes)
Take a program where a controller calls six services in order. Decide if a facade helps, write it, and say what moved.
Done when: the controller has one call, and a note says what the facade holds and what it does not.
Hint
The facade holds the order, not the rules.
Hard 3: All three (90 minutes)
Design a notification feature that needs: a vendor SMS API with a different interface, logging around every send, and one simple notifyUser call for the app. Name the pattern for each part.
Done when: a diagram shows an adapter, a decorator and a facade, each with its reason.
Hint
The adapter is at the edge, the decorator wraps the adapter, the facade is on top.