Definition-defines a family of algorithms, encapsulate each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Key points: separate different parts/behaviors and encapsulate each part/behavior
Advantage: not only does it let you encapsulate a family of algorithms into their own set of classes, but it also lets you change behavior at runtime .
Example1 (quote from First Head In Design Pattern) :
//inteface code
public interface FlyBehavior ... {
public void Fly();
}
// QuakeBehavior.java
public interface QuakeBehavior ... {
public void Quake();
}
// Duck.java
public abstract class Duck ... {
FlyBehavior flyBehavior;
QuakeBehavior quakeBehavior;
public void performFly()
...{
flyBehavior.Fly();
}
public void performQuake()
...{
quakeBehavior.Quake();
}
public abstract void Display();
public void SetFlyBehavior(FlyBehavior flyb)
...{
this.flyBehavior = flyb;
}
public void SetQuakeBehavior(QuakeBehavior quakeb)
...{
this.quakeBehavior = quakeb;
}
}
public void Fly() ...{
System.out.println("Fly with wings");
}
}
public class FlyWithNoWings implements FlyBehavior ... {
public void Fly() ...{
System.out.println("Fly without wings");
}
}
public class NormalQuake implements QuakeBehavior ... {
@Override
public void Quake() ...{
System.out.println("Normal Quake");
}
}
public class MuteQuake implements QuakeBehavior ... {
@Override
public void Quake() ...{
// TODO Auto-generated method stub
System.out.println("Mute Quake");
}
}
public class MallardDuck extends Duck ... {
@Override
public void Display() ...{
// TODO Auto-generated method stub
System.out.println("I'm Mallard Duck");
}
}
public class MiniDuckSimulator extends Duck ... {
@Override
public void Display() ...{
// TODO Auto-generated method stub
System.out.println("I'm mini-duck");
}
}
//display result
public static void main(String[] args) ...{
// TODO Auto-generated method stub
Duck mallardDuck=new MallardDuck();
Duck miniDuck=new MiniDuckSimulator();
FlyBehavior flyWithWings=new FlyWithWings();
FlyBehavior flyWithNoWings=new FlyWithNoWings();
QuakeBehavior normalQuake=new NormalQuake();
QuakeBehavior muteQuake=new MuteQuake();
//Customize
mallardDuck.SetFlyBehavior(flyWithWings);
mallardDuck.SetQuakeBehavior(normalQuake);
miniDuck.SetFlyBehavior(flyWithNoWings);
miniDuck.SetQuakeBehavior(muteQuake);
//perfomance and display
mallardDuck.Display();
mallardDuck.performFly();
mallardDuck.performQuake();
miniDuck.Display();
miniDuck.performFly();
miniDuck.performQuake();
}
}
Example2 (talk about PetShop4.0 developed by MS):
When inserting Order, PetShop System enable user customize which strategy he want to use, synchronization or asynchronization. i.e. the insert-order strategy is changeable at runtime, determined by user himself.