In this example I´m going to explane the strategy pattern. With this example you can do a calculation with two numbers (-/+) and expand the number of operators (/, *, etc.).
First create a interface which defines the interface of the operator classes. For this example an operator can only calculate two values.
[code language=’c#’]
//The interface for the strategies
public interface ICalculateInterface
{
//define method
int Calculate(int value1, int value2);
}
[/code]
Next create the operators (strategies) Minus (which subtract value 2 from value 1) and Plussus (which addition value 1 with value 2). The classes need to inherit from the interface ICalculateInterface.
[code language=’c#’]
//Strategy 1: Minus
class Minus : ICalculateInterface
{
public int Calculate(int value1, int value2)
{
//define logic
return value1 – value2;
}
}
//Strategy 2: Plussus
class Plussus : ICalculateInterface
{
public int Calculate(int value1, int value2)
{
//define logic
return value1 + value2;
}
}
[/code]
At last we need to create a Client that will execute the strategy.
[code language=’c#’]
//The client
class CalculateClient
{
private ICalculateInterface calculateInterface;
//Constructor: assigns strategy to interface
public CalculateClient(ICalculateInterface strategy)
{
calculateInterface = strategy;
}
//Executes the strategy
public int Calculate(int value1, int value2)
{
return calculateInterface.Calculate(value1, value2);
}
}
[/code]
Now we have two operators (minus & plussus) and a client (CalculateClient) that can execute the operators. Let’s test the code. Create a new webapplication, console app or something else that can write output. For this example I will use a webpage.
Initialize a new CalculateClient with argument operator Minus of Plussus and Calculate two values.
[code language=’c#’]
protected void Page_Load(object sender, EventArgs e)
{
CalculateClient minusClient = new CalculateClient(new Minus());
Response.Write(“
Minus: ” + minusClient.Calculate(7, 1).ToString());
CalculateClient plusClient = new CalculateClient(new Plussus());
Response.Write(“
Plussus: ” + plusClient.Calculate(7, 1).ToString());
}
[/code]
This code will give the following output.
[code language=’html’]
Minus: 6
Plussus: 8
[/code]
The great thing about this pattern is that you can easily add new opertators (strategies) to your code.
Cheers,
Pieter