- Behavioral design pattern
- The intent of this pattern is to define a family of algorithms, encapsulate each one , and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
- Context is configured with a concretestrategy object maintains a reference to a strategy object.
- Strategy declares an interface common to all supported algorithms. Context uses it to call the algorithm defined by concretestrategy
ORDER.CS
namespace strategypattern
{
public class Order
{
public string OrderId { get; set; }
public string ProductName { get; set; }
public string ProductDisplayName { get; set; }
public string ProductPrice { get; set; }
public IDownloadOrder DownloadOrderService { get; set; }
public Order(string orderId, string productName, string productDisplayName, string productPrice)
{
OrderId = orderId;
ProductName = productName;
ProductDisplayName = productDisplayName;
ProductPrice = productPrice;
//you can set default value in the constructor
//downloadOrderService = new JSONDownloadOrder;
//or
//directly pass as parameter to the constructor
//public Order(string orderId, string productName, string productDisplayName, string productPrice,IDownloadOrder downloadOrderService)
}
public void Download()
{
DownloadOrderService.Download(this);
}
}
}
DownloadOrder.cs
namespace strategypattern
{
public interface IDownloadOrder
{
void Download(Order order);
}
public class XMLDownloadOrder : IDownloadOrder
{
public void Download(Order order)
{
Console.WriteLine("downloading order as xml");
}
}
public class JSONDownloadOrder : IDownloadOrder
{
public void Download(Order order)
{
Console.WriteLine("downloading order as JSON");
}
}
public class CSVDownloadOrder : IDownloadOrder
{
public void Download(Order order)
{
Console.WriteLine("downloading order as CSV");
}
}
}
PROGRAM.CS
using strategypattern;
var order = new Order("123", "ps5", "ps5 console", "54990");
order.DownloadOrderService = new JSONDownloadOrder();
order.Download();
OUTPUT
downloading order as JSON
GITHUB