Strategy Design Pattern Overview
- Defines a family of algorithms, encapsulates each one, and makes them interchangeable.
- Identify the aspects of your application that vary and separate them from what stays the same.
- The varying aspect is pulled out so it can be reused (avoid code duplication).
- No modification on Dog classes required when adding new or modifying existing bark behavior.
- Dynamically change bark behavior during runtime.
Before
public class Dog {
public void bark() {
System.out.println("grr");
};
public void intro() {
System.out.println("Dog is a domesticated carnivorous mammal.");
}
}
public class GermanShepherd extends Dog {
@Override
public void bark() {
System.out.println("woof");
}
@Override
public void intro() {
System.out.println("German Shepherds are working dogs developed originally for herding sheep.");
}
}
public class GoldenRetriever extends Dog {
@Override
public void bark() {
System.out.println("woof");
}
@Override
public void intro() {
System.out.println("Golden Retriever are gun dogs trained to retrieve shot waterfowl such as ducks.");
}
}
public class RubberDog extends Dog {
@Override
public void bark() {
System.out.println("I can't bark.");
}
@Override
public void intro() {
System.out.println("A toy used in bath.");
}
}
public class Simulator {
public static void main(String[] args) {
Dog dog = new RubberDog();
dog.bark(); // I can't bark.
}
}
After
interface BarkBehavior {
void bark();
}
public class BarkGrr implements BarkBehavior {
@Override
void bark() {
System.out.println("grr");
}
}
public class BarkMute implements BarkBehavior {
@Override
void bark() {
System.out.println("I can't bark.");
}
}
public class BarkWoof implements BarkBehavior {
@Override
void bark() {
System.out.println("woof");
}
}
public class Dog {
BarkBehavior barkBehavior;
public void setBarkBehavior(BarkBehavior bb) {
barkBehavior = bb;
}
public Dog() {
barkBehavior = new BarkGrr();
}
public void bark() {
barkBehavior.bark();
};
public void intro() {
System.out.println("Dog is a domesticated carnivorous mammal.");
}
}
public class GermanShepherd extends Dog {
public GermanShepherd() {
barkBehavior = new BarkWoof();
}
@Override
public void intro() {
System.out.println("German Shepherds are working dogs developed originally for herding sheep.");
}
}
public class GoldenRetriever extends Dog {
public GoldenRetriever() {
barkBehavior = new BarkWoof();
}
@Override
public void intro() {
System.out.println("Golden Retriever are gun dogs trained to retrieve shot waterfowl such as ducks.");
}
}
public class RubberDog extends Dog {
public RubberDog() {
barkBehavior = new BarkMute();
}
@Override
public void intro() {
System.out.println("A toy used in bath.");
}
}
public class Simulator {
public static void main(String[] args) {
Dog dog = new RubberDog();
dog.bark(); //I can't bark.
dog.setBarkBehavior(new BarkWoof());
dog.bark(); //woof
}
}