Design Pattern - Behavioral - Strategy

Scenario:

Create a Currency Helper to add the currency symbol based on country

Solution:

Behavioral Pattern is used to select an algorithm at runtime by dynamic parameter for example.

Example: Create a Currency Helper to add the currency symbol based on country
    public interface ICurrencyStrategy
    {
        string ToCurrency(long value);
    }
    
    public static class CurrencyCodes
    {
        public const string USD = "$";
        public const string INR = "₹";
    }
    
    public class USCurrencyStrategy : ICurrencyStrategy
    {
        public string ToCurrency(long value)
        {
            return $"{CurrencyCodes.USD} {value}";
        }
    }
    
    public class IndiaCurrencyStrategy : ICurrencyStrategy
    {
        public string ToCurrency(long value)
        {
            return $"{CurrencyCodes.INR} {value}";
        }
    }
    
    public class Currency
    {
        public long Value { get; set; }
    
        public Currency(long value)
        {
            Value = value;
        }
    
        public string ToCurrency()
        {
            ICurrencyStrategy currencyStrategy = ResolveStrategyByCountry();
            return currencyStrategy.ToCurrency(Value);
        }
    
        private ICurrencyStrategy ResolveStrategyByCountry()
        {
            if (CultureInfo.CurrentCulture.Name == "en-US")
            {
                return new USCurrencyStrategy();
            }
    
            if (CultureInfo.CurrentCulture.Name == "en-IN")
            {
                return new IndiaCurrencyStrategy();
            }
    
            return null;
    }

        public class StrategyPattern
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Enter key U for US or I for India");
    
                var key = Console.ReadKey();
    
                switch (key.Key)
                {
                    case ConsoleKey.U:
                        System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                        break;
                    case ConsoleKey.I:
                        System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-IN");
                        break;
                }
    
                var price = new Currency(44);
    
                Console.WriteLine($"{price.ToCurrency()}");
            }
        }

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...