Strategy Pattern Article Index for
Strategy
Website Links For
Strategy
 

Information About

Strategy Pattern




The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.


EXAMPLE


Sample Code in C#;
Strategy - Interface: The classes that implement a concrete strategy should implement it. The context class uses this to call the concrete strategy.
ConcreteStrategy: Implements the algorithm using the strategy interface.
Context: configured with a ConcreteStrategy object and maintains a reference to a Strategy object


using System;

namespace Wikipedia.Patterns.Strategy
{

// MainApp test application
class MainApp
{
static void Main()
{
Context context;

// Three contexts following different strategies
context = new Context(new ConcreteStrategyA());
context.Execute();

context = new Context(new ConcreteStrategyB());
context.Execute();

context = new Context(new ConcreteStrategyC());
context.Execute();

Console.Read();
}
}

// "Strategy"
interface Strategy
{
void Execute();
}

// "ConcreteStrategyA"
class ConcreteStrategyA : Strategy
{
public void Execute()
{
Console.WriteLine(
"Called ConcreteStrategyA.Execute()");
}
}

// "ConcreteStrategyB"
class ConcreteStrategyB : Strategy
{
public void Execute()
{
Console.WriteLine(
"Called ConcreteStrategyB.Execute()");
}
}

// "ConcreteStrategyC"
class ConcreteStrategyC : Strategy
{
public void Execute()
{
Console.WriteLine(
"Called ConcreteStrategyC.Execute()");
}
}

// "Context"
class Context
{
Strategy strategy;

// Constructor
public Context(Strategy strategy)
{
this.strategy = strategy;
}

public void Execute()
{
strategy.Execute();
}
}
}



SEE ALSO



EXTERNAL LINKS