Programming - Strategy Behavioral Design Pattern
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
The classes and/or objects participating in this pattern are:
-
Strategy
-
ConcreteStrategy
-
Context
-
is configured with a ConcreteStrategy object
-
maintains a reference to a Strategy object
-
may define an interface that lets Strategy access its data.
using
System;
namespace DoFactory.GangOfFour.Strategy.Structural
{
// MainApp test application
class MainApp
{
static void Main()
{
Context context;
// Three contexts following different strategies
context = new Context(new ConcreteStrategyA());
context.ContextInterface();
context = new Context(new ConcreteStrategyB());
context.ContextInterface();
context = new Context(new ConcreteStrategyC());
context.ContextInterface();
// Wait for user
Console.Read();
}
}
// "Strategy"
abstract class Strategy
{
public abstract void AlgorithmInterface();
}
// "ConcreteStrategyA"
class ConcreteStrategyA : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine(
"Called ConcreteStrategyA.AlgorithmInterface()");
}
}
// "ConcreteStrategyB"
class ConcreteStrategyB : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine(
"Called ConcreteStrategyB.AlgorithmInterface()");
}
}
// "ConcreteStrategyC"
class ConcreteStrategyC : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine(
"Called ConcreteStrategyC.AlgorithmInterface()");
}
}
// "Context"
class Context
{
Strategy strategy;
// Constructor
public Context(Strategy strategy)
{
this.strategy = strategy;
}
public void ContextInterface()
{
strategy.AlgorithmInterface();
}
}
}
Output expected:
Called ConcreteStrategyA.AlgorithmInterface()
Called ConcreteStrategyB.AlgorithmInterface()
Called ConcreteStrategyC.AlgorithmInterface()
Other pages of interest:
Comments(0)
Add Comment