|
In this exercise, we will explore the Strategy design pattern and how it affects our programs. We will encounter a number of issues:
We will study a classic "Ballworld" animation where Ball class objects "bounce" around the screen. The supplied implementation is fully object-oriented and uses a number of subclasses of Ball that display variety of different behaviors, such as curving trajectories and changing radii ("breathes"). While this is all well and good, this inheritance-based architecture is actually quite restrictive. For instance, suppose one wanted to create a Ball subclass that both curves and breathes. We could copy the relevant code from the existing subclasses classes and paste it into a new subclass. But this replication of code can cause some serious maintainablility and upgradability problems. This inheritance-based model also rules out dynamically composed behavior as it would be too hard to effectively implement. To solve this problem, we will examine the subclasses and discover that we can completely isolate the differing (variant) behaviors of each subclass and in turn, describe the Ball superclass in terms of purely unchanging (invariant) behavior. We will encapsulate the invariant behaviors into a single Ball class coupled with an abstract "strategy" class. The specific and variant behaviors are represented by concrete subclasses of the abstract strategy. This Strategy Design pattern models this separation of the variant and invariant behaviors very nicely. This basic design patter and proves to be a very useful pedagogical tool to help students learn this and other OO concepts, including inheritance, polymorphism, abstraction, composition, indirection and encapsulation. This exercise is adapted from one of the weekly laboratory assignments given to Stephen Wong's introductory CS150 "Principles of Computer Science" course at Oberlin College. The students spend the first and second weeks of class getting the Ballworld animation to work and in creating the inheritance-based architecture. The switch to using a Strategy pattern takes place during the third and fourth weeks of class.
|