Definition:
Identify the aspects of your application that vary and separate them from what stays the same
Sample Code:
namespace StrategyPattern { public abstract class Duck { protected FlyBehavior flyBehavior; protected QuackBehavior quackBehavior; public Duck() { } public abstract void display(); public void swim() { Console.WriteLine("All ducks float"); } public void performFly() { flyBehavior.fly(); } public void performQuack() { quackBehavior.quack(); } public void setFlyBehavior(FlyBehavior behavior) { flyBehavior = behavior; } public void setQuackBehavior(QuackBehavior behavior) { quackBehavior = behavior; } } public interface FlyBehavior { void fly(); } public interface QuackBehavior { void quack(); } public class FlyWithWings : FlyBehavior { public void fly() { Console.WriteLine("Fly with wings"); } } public class FlyNoWay : FlyBehavior { public void fly() { Console.WriteLine("Do nothing"); } } public class Quack : QuackBehavior { public void quack() { Console.WriteLine("Duck is quacking"); } } public class Squeak : QuackBehavior { public void quack() { Console.WriteLine("Duck is squeaking"); } } public class MuteQuack : QuackBehavior { public void quack() { Console.WriteLine("Do nothing"); } } public class MallarDuck : Duck { public MallarDuck() { flyBehavior = new FlyWithWings(); quackBehavior = new Quack(); } public override void display() { Console.WriteLine("This is a real Mallard duck"); } } }
Usage:
static void CallStrategy() { MallarDuck duck = new MallarDuck(); //Perform the default behaviors assigned in construct duck.performFly(); duck.performQuack(); //Change the hehaviors during runtime duck.setFlyBehavior(new FlyNoWay()); duck.setQuackBehavior(new MuteQuack()); duck.performFly(); duck.performQuack(); }
Class Diagram: