Simple Factory Pattern

  • In program.cs – we are creating the respective ITotalCost service concrete class.
  • Ideally this class should not be responsible for creating this object
  • Move it to separate static class, have a static method.
  • Invoke the static method… 
  • simple factory is just moving to different class …thats it
				
					var ddownValue = "state";
ITotalCost coachingObj;

coachingObj = ddownValue switch
{
    "state" => new StateWiseMBBSCoachingCost("WB"),
    "coupon" => new CouponApplyMBBSCoachingCost(new Guid()),
    _ => new StateWiseMBBSCoachingCost("Odisha"),
};

Console.WriteLine(coachingObj.TotalCost);//20000
				
			
				
					namespace simple_factory
{
    interface ITotalCost
    {
        decimal TotalCost { get; }
    }

   
    internal class StateWiseMBBSCoachingCost : ITotalCost
    {
        private readonly string _stateCode;
        public StateWiseMBBSCoachingCost(string stateCode)
        {
            _stateCode = stateCode;
        }
        public decimal TotalCost
        {
            get
            {
                switch (_stateCode)
                {
                    case "WB":
                        return 25500;
                    case "MP":
                        return 35500;
                    case "Goa":
                        return 15500;
                    default:
                        return 20000;
                }
            }
        }
    }


    internal class CouponApplyMBBSCoachingCost : ITotalCost
    {
        private readonly Guid _couponCode;
        public CouponApplyMBBSCoachingCost(Guid couponCode)
        {
            _couponCode = couponCode;
        }
        public decimal TotalCost
        {
            get
            {
                //check for cup
                return 5000;
            }
        }
    }
}
				
			

coachingObj = simpleFactory.createMBBSCoachingService(ddownValue);

				
					var ddownValue = "state";
ITotalCost coachingObj;
coachingObj = simpleFactory.createMBBSCoachingService(ddownValue);
Console.WriteLine(coachingObj.TotalCost);//25500
				
			
				
					namespace simple_factory
{
    internal static class simpleFactory
    {
        public static ITotalCost createMBBSCoachingService(string ddownvalue)
        {
            switch (ddownvalue)
            {
                case "state":
                    return new StateWiseMBBSCoachingCost("WB");
                case "coupon":
                    return new CouponApplyMBBSCoachingCost(new Guid());
                default:
                    return new StateWiseMBBSCoachingCost("Odisha");
            }
        }
    }
}

				
			

25500

Leave a Comment