I am learning design patterns and this is my sample code where I have implemented Factory pattern and instance creation I have delegated to Unity container Framework(DI) to build the loosely coupled system.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Unity; namespace DesignPatternsDemo { class Program { static void Main(string[] args) { iPaymentGateway gateway = PaymentGatwayFactory.NewPaymentGatway(GateWay.SHIFT4); gateway.CreatePaymentGateway(); gateway = PaymentGatwayFactory.NewPaymentGatway(GateWay.WELLSFARGO); gateway.CreatePaymentGateway(); gateway = PaymentGatwayFactory.NewPaymentGatway(GateWay.PROTOBASE); gateway.CreatePaymentGateway(); Console.ReadLine(); } enum GateWay { PROTOBASE = 1, SHIFT4 = 2, WELLSFARGO = 3 } //Factory class class PaymentGatwayFactory { public static iPaymentGateway NewPaymentGatway(GateWay GateWayType) { //Dependency injection using unity container var container = new UnityContainer(); iPaymentGateway result = null; switch (GateWayType) { case GateWay.SHIFT4: container.RegisterType<iPaymentGateway, SHIFT4Gateway>(); result = container.Resolve<SHIFT4Gateway>(); break; case GateWay.WELLSFARGO: container.RegisterType<iPaymentGateway, WellsFargoGateway>(); result = container.Resolve<WellsFargoGateway>(); break; default: container.RegisterType<iPaymentGateway, ProtobaseGateway>(); result = container.Resolve<ProtobaseGateway>(); break; } return result; } } class WellsFargoGateway : iPaymentGateway { public void CreatePaymentGateway() { Console.WriteLine("Implement Wells Fargo logic"); } } class SHIFT4Gateway : iPaymentGateway { public void CreatePaymentGateway() { Console.WriteLine("Implement SHIFT4 logic"); } } class ProtobaseGateway : iPaymentGateway { public void CreatePaymentGateway() { Console.WriteLine("Implement Protobase logic"); } } interface iPaymentGateway { void CreatePaymentGateway(); } } }
Is this is the right way of implementing Factory pattern and using the Unity framework?