Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: List the families (20 minutes)
A game has two themes, forest and desert, each with its own Tree, Ground and Music. Write the abstract products and the two families.
Done when: you have a table of three kinds by two families.
Hint
Three kinds and two families give six concrete classes.
Easy 2: Run the invoice (20 minutes)
Type the billing code and run it for both regions with an amount of 1000.
Done when: you print "Rs 1180" and "$1080".
Hint
Integer division makes 18 percent of 1000 equal to 180.
Easy 3: Find the factory (20 minutes)
In the billing code, mark the single line where a concrete factory class is named.
Done when: you show that it appears once, in the code that builds Invoice.
Hint
The line is where Invoice is built.
Medium
Medium 1: Add a region (45 minutes)
Add a UK family with a 20 percent tax and a pound format. Do not edit Invoice.
Done when: a new factory prints "£1200" for 1000.
Hint
Implement Tax and Formatter again, plus a factory.
Medium 2: Add a product (45 minutes)
Add a Rounding product to the family. List every file you had to edit.
Done when: you have the list and a sentence on the weakness it shows.
Hint
The interface and every concrete factory change.
Medium 3: Choose from settings (45 minutes)
Write a small main that reads a region code (such as "IN") and picks the factory. Keep all new calls for factories in that one place.
Done when: only main names IndiaFactory and UsFactory.
Hint
A switch on the code returns a RegionFactory.
Hard
Hard 1: Themed screen (90 minutes)
Build a console program with Button and Label products in two themes that print differently. Add a method that prints a screen using only the abstract types.
Done when: switching the theme needs one changed line and the screen code is untouched.
Hint
Pass the factory into the screen's constructor.
Hard 2: Database kit (90 minutes)
Define Connection, Command and Reader products for two fake databases. Make a test that fails if a client mixes products from two families, and explain how the pattern prevents it.
Done when: a test shows consistency by construction.
Hint
A client that gets all products from one factory cannot mix.
Hard 3: Compare three (90 minutes)
Solve the region problem three ways: simple factory, Factory Method, Abstract Factory. Compare how each handles adding a region and adding a product.
Done when: a table has four cells that count the edits, and you choose one with reasons.
Hint
Adding a product is hard for Abstract Factory only.