Thursday, March 11, 2010

Strategy design pattern

Here is a bit of code which illustrates the Strategy Design Pattern:

package raj;

/**
*
* @author Rajeev
*/
public class StrategyTest {

public static void main(String[] arg) {
Animal dog = new Dog();
Animal cat = new Cat();
Animal donkey = new Donkey();
Animal trickDog = new TrickDog();
dog.makeNoise();
cat.makeNoise();
donkey.makeNoise();
trickDog.makeNoise();
}
}

class Animal {

Noise n;

void makeNoise() {
n.makeNoise();
}
}

class Dog extends Animal {

Dog() {
n = new WoofNoise();
}
}

class TrickDog extends Animal {

TrickDog() {
n = new MeowNoise();
}
}

class Cat extends Animal {

Cat() {
n = new MeowNoise();
}
}

class Donkey extends Animal {

Donkey() {
n = new BrayNoise();
}
}

abstract class Noise {

abstract void makeNoise();
}

class BrayNoise extends Noise {

void makeNoise() {
System.out.println("Bray");
}
}

class WoofNoise extends Noise {

void makeNoise() {
System.out.println("Woof");
}
}

class MeowNoise extends Noise {

void makeNoise() {
System.out.println("Meow");
}
}

The key things is that rather than overriding the makeNoise() method of Animal class in all the subclasses we have abstracted out this behaviour in a separate class as it has a number of variations. The Animal class now HAS-A relationship with this Noise algorithm. All the subclasses of Animal set the proper Noise behaviour in their constructor. This allows our TrickDog to magically start meowing. Also this new Noise class can be used in other situations where appropriate.

Also note that rather than using abstract class for Noise we could have defined it as an interface and then implement it in our concrete Noise classes. The logic becomes:

abstract interface Noise {
abstract void makeNoise();
}

class BrayNoise implements Noise {
void makeNoise() {
System.out.println("Bray");
}
}

... and so on.



No comments:

Post a Comment