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.
Strategy Pattern Diagram

Implementation
Creating a Duck interface:
public abstract class Duck {
/* The behavior variables are declared as the behavior INTERFACE type
Instance veriables hold a reference to a specific behavior at runtime */
FlyBehavior flyBehavior;
QuackBehavior quackBehavior;
/* Constructor.
The constructor name is equivalent to the class name.
Even if you don't define this, Java defines it by default. */
public Duck() {}
public abstract void display();
/* Replacing fly and quack methods.
Rather than handling the behavior itself, the Duck object delegates
that behavior to the object referened by flyBehavior or quackBehavior */
public void performFly() {
flyBehavior.fly();
}
public void performQuack() {
quackBehavior.quack();
}
public void swim() {
System.out.println("All ducks float even decoys!");
}
/* Seeter methods
With these setters, you can dynamically set behavior of duck at runtime */
public void setFlyBehavior(FlyBehavior fb) {
flyBehavior = fb;
}
public void setQuackBehavior(QuackBehavior qb) {
quackBehavior = qb;
}
}Creating a Concrete instance:
public class MallardDuck extends Duck {
public MallardDuck() {
/* Uses the Quack class to handle its quack, so when performQuack
is called, the responsbility for the quack is delegated to the
Quack object and we get a real quack. */
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
}
public void display() {
System.out.println("I'm a real Mallard duck.");
}
}public class ModelDuck extends Duck {
public ModelDuck() {
flyBehavior = new FlyNoWay();
quackBehavior = new Quack();
}
public void display() {
System.out.println("I'm a model duck");
}
}Creating Behavior interfaces:
public interface QuackBehavior {
public void quack();
}public interface FlyBehavior {
public void fly();
}Creating Concrete Behaviors:
public class FlyWithWings implements FlyBehavior {
public void fly() {
System.out.println("I'm flying");
}
}
public class FlyNoWay implements FlyBehavior {
public void fly() {
System.out.println("I can't fly");
}
}public class Quack implements QuackBehavior {
public void quack() {
System.out.println("Quack");
}
}
public class Squeak implements QuackBehavior {
public void quack() {
System.out.println("Squeak");
}
}Testing:
public class MiniDuckSimulator {
public static void main(String[] args) {
Duck mallard = new MallardDuck();
mallard.performQuack(); // Quack
mallard.performFly(); // I'm flying!
Duck model = new ModelDuck();
model.performFly(); //
model.setFlyBehavior(new FlyRocketPowered());
model.performFly();
}
}