Strategy design pattern enables selecting
strategy at runtime. Strategy Pattern falls under behavioral pattern of GOF
(Gang of Four) patterns.
When to use –
Strategy pattern used to separate different
types of algorithms/processes that shares similar purpose. This decouples code
into multiple classes and promotes reusability. Strategy pattern allows client
to choose strategy/algorithm at runtime that provides more flexibility and
reusability. Strategy pattern is one of the easiest pattern to implement.
Major components of Strategy pattern –
Context – Context
class maintains reference to Strategy object and provides an interface to set
Strategy dynamically.
Strategy –
This is an interface and used by Context object.
Concrete Strategy – This class implements Strategy interface.
Let’s have a look on below example of Strategy
design pattern.
//strategy
public interface IPaymentStrategy
{
void Pay(double amount);
}
//concrete strategy
public class Cash : IPaymentStrategy
{
public void Pay(double amount)
{
Console.WriteLine("{0} paid in cash.", amount);
}
}
//concrete strategy
public class CreditCard : IPaymentStrategy
{
public void Pay(double amount)
{
Console.WriteLine("{0} paid via Credit Card", amount);
}
}
//concrete strategy
public class DebitCard : IPaymentStrategy
{
public void Pay(double amount)
{
Console.WriteLine("{0} paid via Debit Card", amount);
}
}
//context
public class Customer
{
public IPaymentStrategy Strategy { get; set; }
public Customer(IPaymentStrategy strategy)
{
Strategy = strategy;
}
public void Payment(double amount)
{
Strategy.Pay(amount);
}
}
class Program
{
//entry point
static void Main(string[] args)
{
Customer customer = new Customer(new CreditCard());
Console.WriteLine("{0} Current Strategy {1} {2}", new string('-',10),
customer.Strategy.GetType().Name, new string('-', 10));
customer.Payment(200);
customer.Strategy = new Cash();
Console.WriteLine("{0} Current Strategy {1} {2}", new string('-', 10),
customer.Strategy.GetType().Name, new string('-', 10));
customer.Payment(100);
customer.Strategy = new DebitCard();
Console.WriteLine("{0} Current Strategy {1} {2}", new string('-', 10),
customer.Strategy.GetType().Name, new string('-', 10));
customer.Payment(500);
Console.Read();
}
}
In above example, customer wants to pay some
amount and decides between various payments strategies at runtime. There are
three payment strategies Cash, CreditCard, DebitCard available for payment. Initially
Customer object created with CreditCard payment strategy and later on payment strategy
keeps changing as per customer’s decision.
You can download full code from Gist.
I hope this article helps you to know more
about Strategy Design Pattern. Please leave your feedback in comments section
below.
References –
See Also –
Creational Patterns
|
Structural Patterns
|
Behavioral Patterns
|
|
||
|
|
|
|
|
|
|
|
|
|
|