Last active
May 13, 2018 14:15
-
-
Save miteshsureja/e2601d8c5af7c41d090a7fcd0fc79d12 to your computer and use it in GitHub Desktop.
Strategy Design Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Author
miteshsureja
commented
May 13, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment