Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Name the constructors (20 minutes)
Write a Duration class with a constructor that takes a long. Add ofMinutes, ofHours and ofDays static factories.
Done when: Duration.ofHours(2) and Duration.ofMinutes(120) hold the same value.
Hint
Store everything in minutes inside the class.
Easy 2: Run the factories (20 minutes)
Type the NotifierFactory, Money and Checkout code of this page and run each.
Done when: you print sms:hi, unknown kind: FAX, Money[paise=500] and the two receipts.
Hint
The switch needs a default branch.
Easy 3: Label the three (20 minutes)
For Boolean.valueOf, Collections.unmodifiableList and a Checkout with createReceipt, write which of the three ideas each is.
Done when: each has a label and one line of reason.
Hint
Only one of the three has a subclass choosing the product.
Medium
Medium 1: Add push (45 minutes)
Add a Push notifier to the simple factory. Then replace the switch with a Map<String, Supplier<Notifier>>.
Done when: the map version passes the same calls and a new kind is one map entry.
Hint
Supplier<Notifier> is Email::new.
Medium 2: Parking fee creator (45 minutes)
Write an abstract ParkingLot with createFeeRule() and a method exitFee(int hours) that uses it. Add MallLot and AirportLot with different rules.
Done when: exitFee is written once, and two subclasses return different fees for 3 hours.
Hint
The factory method is called inside exitFee.
Medium 3: Cache with a static factory (45 minutes)
Write a Colour value class with a private constructor and Colour.of(String name) that returns the same instance for the same name.
Done when: Colour.of("red") == Colour.of("red") is true.
Hint
Keep a Map<String, Colour> in the class.
Hard
Hard 1: Hidden classes (90 minutes)
Build a Shapes interface with static factories circle(r) and square(s) that return package-private classes. Show that a caller outside the package cannot name those classes.
Done when: a second package uses the shapes through the interface only, and an attempt to name the class fails to compile.
Hint
Leave the classes without the public keyword.
Hard 2: Replace a switch (90 minutes)
Take a method with a switch over six account types that returns a fee. Redesign it with Factory Method, and with a map. Compare the two.
Done when: both versions run, and a table lists classes added, lines changed for a seventh type, and readability.
Hint
Count files and lines for the seventh type.
Hard 3: When not to (90 minutes)
Write a note of 150 words on a case in a program of your own where a factory would be too much, and name the sign that would change your mind.
Done when: the note has one example, one cost of the factory and one trigger.
Hint
A creation that never varies needs no factory.