This is a simple example of how to use C# Strategy Pattern step by step. The repository contains three different solutions and all the solutions work perfectly with the same expected result. Scope of this repository is to show how to refactor code by using Strategy Pattern info.
Let us see in detail:
- Mandate Basic: basic code
- Mandate Class: use of classes in accordance to SOLID principles
- Mandate Strategy: implementation of statergy pattern
- Shared: C# class to use across the above projects.
Let us consider in a banking environment the mandate creation process. Each portfolio has a mandate type value (Corporation, Private Joint, ...) and the process of mandate creation depends on this.
The process can be simplified in this form, putting in a textbox the desired output:
The basic elaboration in the mandate creation is expected something like this:
var portfolio=.... //gets a portfolio
switch (portfolio.mandateType)
{
case "A":
CreateMandate_for_A();
break;
case "B":
CreateMandate_for_B();
break;
case "C":
CreateMandate_for_C();
break;
}
public void CreateMandate_for_A();
{
// Code to create mandate for mandate type A
}
public void CreateMandate_for_B();
{
// Code to create mandate for mandate type A
}
The first step of refactoring is to give more responsabilities to classes by following the first SOLID principle: Single Responsibility Principle (SRP). In order to do this a class is created for a particular purpose, to generate a mandate for a particular mandate type. In this way each class will have its own method to generate the mandate output.
public class Class_A()
{
public void CreateMandate_for_A();
{
// Code to create mandate for mandate type A
}
}
public class Class_B()
{
public void CreateMandate_for_B();
{
// Code to create mandate for mandate type B
}
}
The third step is to use the above classes following the strategy pattern info. This is class diagram for the strategy pattern and this is what we want to realize:
Following the diagram, the concrete strategies are already implemented and the classes still keep methods for mandate creation.
The next step is to create an interface used by classes with just one method signature:
string RunKYCMandate(Portfolio portfolio);
The last step is to create a Context class passing the interface in the ctor.
public class Context
{
IMandate _mandate;
public Context(IMandate mandate)
{
this._mandate = mandate;
}
public string ContextInterface(Portfolio portfolio)
{
return _mandate.RunKYCMandate(portfolio);
}
}
in this way we can invoke the right mandate creation function simply:
context.ContextInterface(portfolio p)
where p can be an object to Class_A or Class_B.