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.
//The interface for the strategies public interface ICalculateInterface { //define method int Calculate(int value1, int value2); }
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.
//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; } }
At last we need to create a Client that will execute the strategy.
//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); } }
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.
protected void Page_Load(object sender, EventArgs e) { CalculateClient minusClient = new CalculateClient(new Minus()); Response.Write("<br />Minus: " + minusClient.Calculate(7, 1).ToString()); CalculateClient plusClient = new CalculateClient(new Plussus()); Response.Write("<br />Plussus: " + plusClient.Calculate(7, 1).ToString()); }
This code will give the following output.
<br />Minus: 6 <br />Plussus: 8
The great thing about this pattern is that you can easily add new opertators (strategies) to your code.
Cheers,
Pieter