Card 03/ 08
Reading a Pattern's Class Diagram Aloud
Box by box and arrow by arrow, the way you would explain it to a colleague.
A pattern's class diagram is read in a fixed order: first the interfaces and abstract classes, then the classes that implement them, then the class that uses them, and last the arrows that connect them. This card runs that procedure on the diagram of a pattern taught later in this subject, Strategy, without assuming you know the pattern. Reading the diagram is enough to explain it.
Reading the checkout diagram
Find the abstractions
Discount carries the <<interface>> stereotype and one public method, apply(price), which returns a float. Say it aloud: there is a contract for applying a discount to a price, and nothing yet says how.
Find what implements them
Two dashed lines with hollow triangles end at Discount, so TenPercentOff and SeasonalSale both implement it. Each box repeats apply, which tells you each writes its own version.
Find the class that uses them
Checkout has a private field -discount whose type is the interface, not either class. Its public method total(prices) is what the rest of the program calls.
Read the remaining arrows
A solid line with an open arrow runs from Checkout to Discount: an association, so the checkout keeps a discount for as long as it lives. The arrow points at the interface, which means the checkout never names TenPercentOff or SeasonalSale.
Say what the design allows
Put together: a checkout holds one discount, chosen from outside, and calls apply on it for each price. A new discount is a new box with a dashed line to Discount, and Checkout does not change.
The last step is the one that turns a diagram into an explanation. Every pattern diagram is drawn to make some change easy, and asking what can be added without editing an existing box usually finds it. Here it is a new discount, which is exactly the problem the Strategy pattern exists to solve.
← → move through sections and cards