My job makes me move, and l learnt so much from the design pattern. I am gonna review some of them in the last few weeks.(but actually, if you read here. please close this article as quick as you can, I think the best way to study is to read the book but not the blog, The book is gonna give you a more comprehensive tutorial than the blog. Howere you can write some corresponding blogs after the book, which is gonna be a good way to enhance what you have learnt from the book)
the first one of my this series is the Strategy Pattern.
Strategy Pattern:
this pattern is dedicated to predefine some algorithms first, and then those algorithms are eventually implemented by the concrete types. There is also a coordinator to let the client choose the exact concrete type(algorithm).
- We call the one who predefines the algorithms as Strategy.
- The type who implements the Strategy is called as Concrete Strategy.
- The coordinator is called as Context.
This mechanism is terrific, which makes the system more flexible to accustom the system to the frequent changing requirment, also hides the details from the client and makes the system more reusable.
The Context has a reference of the strategy and communicates with the strategy. they decide which concrete stragety is called at the running time with the help of the parameters provided by the client.
So all the clients need to do is to initialize the Context and transfer some parameters as they expected. then everything is going well, the clients don't need to know(actually it is impossible for them to know) exactly how the Context cooperates with the Strategy, even don't know which concrete strategy is called.
Below is a small example to demonstrate what i told above.
Example:
/// <summary>
/// strategy
/// </summary>
public abstract class Strategy
{
public abstract void MyAlgorithm(string para);
}
public class ConcreteStategyA : Strategy
{
public override void MyAlgorithm(string para)
{
// do what A wants
}
}
public class ConcreteStategyB : Strategy
{
public override void MyAlgorithm(string para)
{
// do what B wants
}
}
//.....also you can define C,D,E....anyway
/// <summary>
/// Context
/// </summary>
public class Context
{
private Strategy myStrategy;// has a reference of the Strategy
/// <summary>
/// decide which concrete strategy is called(initialized)
/// </summary>
/// <param name="clientPara"></param>
public Context(string clientPara)
{
switch (clientPara)
{
case "1":
myStrategy = new ConcreteStategyA();
break;
case "2":
myStrategy = new ConcreteStategyB();
break;
//default
}
}
/// <summary>
/// client cares about the "DoSomething"
/// </summary>
/// <param name="clientPara"></param>
public void DoSomethin(string clientPara)
{
myStrategy.MyAlgorithm(clientPara);
}
}
public class MyClient
{
static void Main()
{
Context myContext = new Context("1");//here 1
myContext.DoSomethin("clientPara");//only care "DoSomething"
}
}
Done here.