Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.
Use Case
When your class has massive conditional operator that switches between different variants of an algorithm.
When you want to use different variants of an algorithm within an object and switch from one algorithm to another during runtime.
When you have a lot of similar classes that only differ in the way they execute some behavior.
Code
Assume we are building shipping management system.
We have an order that needs to be shipped to the customer by specific shipping method.
//Class to store order detailspublicclassOrder{publicintId{get;set;}publicdoubleWeight{get;set;}publicdoubleAmount{get;set;}}
//Interface to define the strategy for shippingpublicinterfaceIShippingStrategy{stringProviderName{get;set;}doubleCalculateCost(Orderorder);}publicclassFedExShippingStrategy:IShippingStrategy{publicstringProviderName{get;set;}="FedEx";publicdoubleCalculateCost(Orderorder){returnorder.Weight*0.5+order.Amount*0.1;}}publicclassUPSShippingStrategy:IShippingStrategy{publicstringProviderName{get;set;}="UPS";publicdoubleCalculateCost(Orderorder){returnorder.Weight*0.6+order.Amount*0.2;}}publicclassAmazoneShippingStrategy:IShippingStrategy{publicstringProviderName{get;set;}="Amazone";publicdoubleCalculateCost(Orderorder){returnorder.Weight*0.4+order.Amount*0.15;}}
//Class to process oroder shipping using strategy patternpublicclassOrderProcessor{privatereadonlyDictionary<string,IShippingStrategy>_shippingStrategies;publicOrderProcessor(List<IShippingStrategy>shippingStrategies){_shippingStrategies=newDictionary<string,IShippingStrategy>();foreach(varstrategyinshippingStrategies){_shippingStrategies[strategy.ProviderName]=strategy;}}publicvoidCalculateShippingCost(Orderorder,stringproviderName){if(_shippingStrategies.TryGetValue(providerName,outvarstrategy)){doubleshippingCost=strategy.CalculateCost(order);Console.WriteLine($"Order ID: {order.Id}, Shipping Provider: {strategy.ProviderName}, Shipping Cost: {shippingCost}");}else{Console.WriteLine($"Shipping provider '{providerName}' not found.");}}}