Saturday, October 6, 2007

Strategy pattern (3)

Now that's test our program:

Duck newDuck = new MallardDuck();
newDuck.PerformFly();
//I'm flying with wings!!
newDuck.setFlyBehavior(new FlyNoWay()); //setting behavior dynamically
newDuck.PerformFly(); //I can't fly.

So we have ducks extending Duck, fly behaviors implementing IFlyBehavior and quack behaviors implementing IQuackBehavior. Now instead of thinking of the duck behaviors as a set of behaviors, we'll start thinking of them as a family of algorithms. The algorithms represent things a duck would do (different ways of quacking or flying), but we could just as easily use the same techniques for a set of classes that implement the ways to compute state sales tax by different states.

As you can see from above test program, because we've taken out the behaviors out of the Duck class, we can dynamically change behavior at runtime, this is actually the key to our first pattern - "Strategy Pattern":

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
blog comments powered by Disqus