PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 11 ■ PERFORMING AND REPRESENTING TASKS

Figure 11–4. Defining subclasses according to two forces


Not only have the number of classes in the hierarchy ballooned, but you also necessarily introduce
repetition. Your marking logic is reproduced across each branch of the inheritance hierarchy.
Whenever you find yourself repeating an algorithm across siblings in an inheritance tree (whether
through subclassing or repeated conditional statements), consider abstracting these behaviors into their
own type.


Implementation


As with all the best patterns, Strategy is simple and powerful. When classes must support multiple
implementations of an interface (multiple marking mechanisms, for example), the best approach is
often to extract these implementations and place them in their own type, rather than to extend the
original class to handle them.
So, in the example, your approach to marking might be placed in a Marker type. Figure 11–5 shows
the new structure.
Remember the Gang of Four principle “favor composition over inheritance”? This is an excellent
example. By defining and encapsulating the marking algorithms, you reduce subclassing and increase
flexibility. You can add new marking strategies at any time without the need to change the Question
classes at all. All Question classes know is that they have an instance of a Marker at their disposal, and
that it is guaranteed by its interface to support a mark() method. The details of implementation are
entirely somebody else’s problem.

Free download pdf