Strategy – It allows the programs to define a family of an algorithm, put each one into a separate class, and make their objects interchangeable.
From Design Pattern – Behavioral Patterns
Structure
Applicability
Pros and Cons
PROS
CONS
How to Implement
#1 Basic Sample
static void Main(string[] args)
{
var context = new Context();
context.SetStrategy(new ConcreteStrategyA());
context.DoSomething();
context.SetStrategy(new ConcreteStrategyB());
context.DoSomething();
Console.ReadKey();
}
public class Context
{
private IStrategy _strategy;
public Context() { }
public Context(IStrategy strategy) => _strategy = strategy;
public void SetStrategy(IStrategy strategy) => _strategy = strategy;
public void DoSomething()
{
var result = this._strategy.DoAlgorithm(new List<string> { "a", "b", "c", "d", "e" });
string resultStr = string.Empty;
foreach (var element in result as List<string>)
{
resultStr += element + ",";
}
Console.WriteLine(resultStr);
}
}
public interface IStrategy
{
object DoAlgorithm(object obj);
}
public class ConcreteStrategyA : IStrategy
{
public object DoAlgorithm(object obj)
{
var list = obj as List<string>;
list.Sort();
return list;
}
}
public class ConcreteStrategyB : IStrategy
{
public object DoAlgorithm(object obj)
{
var list = obj as List<string>;
list.Sort();
list.Reverse();
return list;
}
} #2 Web Application Project
Step 1 Create the two interface class files in the Core projects. One interface class file name sets “IStrategy.” Another interface class file name sets “IStrategyServices.”
Step 2 Create the three class files. One class file name sets “StrategyContext.” Another class file name sets “ConcreteStrategySort.” Other class file name sets “ConcreteStrategyReverse.” The “ConcreteStrategySort” and the “ConcreteStrategyReverse” inherit the “IStrategy” interface class files.
Step 3 Create the service class file for the strategy pattern. This class file name sets “StrategyServices,” inheriting the “IStrategyServices” interface class files.
Step 4 Create the strategy pattern-related files in the web projects and register the Core project’s class file in the “Startup.cs” file.
// Strategy
services.AddScoped(typeof(IStrategyServices<>), typeof(StrategyServices<>)); Reference
What is the API gateway? An API gateway is an API management tool that sits…
The .NET 5 SDK is a kind of milestone in the .NET world. The .NET…
In object-oriented design, the dependency inversion principle is a specific methodology for loosely coupling software…
In the field of software engineering, the interface segregation principle (ISP) states that no code…
Subtype Requirement: Let be a property provable about objects of type T. Then should be true for objects of type S where S is…
In object-oriented programming, the open–closed principle states "software entities (classes, modules, functions, etc.) should be…
View Comments