5.1 Strategy

The Strategy pattern is an example of delegation, the general object-oriented idiom that was mentioned in the last chapter. Before starting, we should mention that in discussing implementations of patterns such as the Strategy pattern it will be helpful to use obvious, illustrative class names like Context and Strategy, as in Figure 5.2. But of course when you use the software patterns in your own code you can call your classes anything you like.

Figure 5.2. The Strategy pattern


The problem addressed by the Strategy pattern is when we have a range of objects, all members of the same class called, let's say, Context, and we want to be able to change the behavior of the behave method of a Context object without having to change the class the object belongs to.

The solution is to create a Strategy class that holds a behavealgorithm method. The Context class will have a Strategy *_pstrategy member, and a Context::behave(){_pstrategy->behavealgorithm(this)}.

The reason you need to pass the 'this' to the behavealgorithm is so that the method can use the Context mutators and accessors to view and to alter the data of the Context object. Possibly behavealgorithm may call some other Context methods as well.

If you find it useful, you can use the same name for the Context::behave() and Strategy::behavealgorithm methods.

The Strategy pattern plays a role similar to the role of function pointers in old-style C programming. One of the motivations for using the Strategy pattern is to avoid having a combinatorial explosion of classes. Rather than having to derive off new subclasses for new kinds of behavior, we use the Strategy pattern to let classes 'plug-in' whatever behavior they need.

In the Pop Framework, the cCritter::feellistener() method calls a cListener::lis ten(cCritter *pcritter) method. In particular, we give each cCritter a cListener *_plis tener. The cCritter::feellistener() calls _plistener->listen(this).

The cListener::listen(cCritter *pcritter) method takes input from the mouse or keyboard and affects the owner critter in different ways.

The fact that a Strategy object can be dynamically changed means that when you are running the Pop program, for instance, you can use the Player menu to select different kinds of controllers for the player. When you are doing this, you change the player's listening strategy.

    Part I: Software Engineering and Computer Games
    Part II: Software Engineering and Computer Games Reference