Skip to content

Instantly share code, notes, and snippets.

@miteshsureja
Last active May 13, 2018 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miteshsureja/e2601d8c5af7c41d090a7fcd0fc79d12 to your computer and use it in GitHub Desktop.
Save miteshsureja/e2601d8c5af7c41d090a7fcd0fc79d12 to your computer and use it in GitHub Desktop.
Strategy Design Pattern
using System;
namespace StrategyPattern
{
//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();
}
}
}
@miteshsureja
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment