Define a family of algorithms, encapsulate each one,
and make them interchangeable. Strategy lets the algorithm vary independently
from clients that use it.
Participants
The classes and/or objects
participating in this pattern are:
- Strategy(Sort Strategy)
Declares an interface common to all supported
algorithms. Context uses this interface to call the algorithm defined by a
Concrete Strategy
- Concrete Strategy (Quick Sort, Shell Sort, Merge Sort)
Implements the algorithm using the Strategy interface
- Context (Sorted List)
Is configured with a Concrete Strategy object
Maintains a reference to a Strategy object
May define an interface that lets Strategy access its
data.
Example for Strategy Design Pattern
Example for Strategy Design Pattern
using System;
namespace
Strategy.Structural
{
/// <summary>
/// MainApp
startup class for Structural
/// Strategy
Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry
point into console application.
/// </summary>
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.ReadKey();
}
}
/// <summary>
/// The
'Strategy' abstract class
/// </summary>
abstract class Strategy
{
public abstract void AlgorithmInterface();
}
/// <summary>
/// A
'ConcreteStrategy' class
/// </summary>
class ConcreteStrategyA : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine(
"Called
ConcreteStrategyA.AlgorithmInterface()");
}
}
/// <summary>
/// A
'ConcreteStrategy' class
/// </summary>
class ConcreteStrategyB : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine(
"Called
ConcreteStrategyB.AlgorithmInterface()");
}
}
/// <summary>
/// A
'ConcreteStrategy' class
/// </summary>
class ConcreteStrategyC : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine(
"Called
ConcreteStrategyC.AlgorithmInterface()");
}
}
/// <summary>
/// The
'Context' class
/// </summary>
class Context
{
private Strategy _strategy;
//
Constructor
public Context(Strategy strategy)
{
this._strategy
= strategy;
}
public void ContextInterface()
{
_strategy.AlgorithmInterface();
}
}
}
|
Output:
Called
ConcreteStrategyA.AlgorithmInterface()
Called ConcreteStrategyB.AlgorithmInterface() Called ConcreteStrategyC.AlgorithmInterface() |
No comments:
Post a Comment