Generic Factory pattern - to switch between Mock and Production environment service

Factory pattern - in my previous article, I explain the factory in detail. One thing came up in my mind about generic factory pattern. This is really handy to have in project. For example if we are working in a environment where service could be tested in Mock or Production environment. And also Mock and Production services using common contracts. So this is a good candidate of Generic Factory. In this article, I will include few sample contracts, production and mock implementation of those contracts, a Service Factory and Test class.
public interface IServiceProxyOne { void ProcessRequest(string data);   }
public interface IServiceProxyTwo { void ProcessRequest(string data);    }
 
public class ServiceProxyOne : IServiceProxyOne
{
  public void ProcessRequest(string data) { /* do something.*/}
}
public class ServiceProxyTwo : IServiceProxyTwo
{
  public void ProcessRequest(string data) { /* do something.*/}
}
 
public class MockServiceProxyOne : IServiceProxyOne
{
  public void ProcessRequest(string data) { /* do something.*/}
}
public class MockServiceProxyTwo : IServiceProxyTwo
{
  public void ProcessRequest(string data) { /* do something.*/}
}
Service Factory implementation code is below,
public static class ServiceFactory
{
     public static IServiceProxyOne CreateServiceProxyOne()
     {
       return GetProxyInstance<IServiceProxyOneMockServiceProxyOneServiceProxyOne>();
     }

     public static IServiceProxyTwo CreateServiceProxyTwo()
     {
       return GetProxyInstance<IServiceProxyTwoMockServiceProxyTwoServiceProxyTwo>();
     }
 
     public static T1 GetProxyInstance<T1, T2, T3>()
            where T2 : T1, new()
            where T3 : T1, new()
     {
       return IsMockEnvironment() ? (T1)new T2() : (T1)new T2();
     }
 
     public static bool IsMockEnvironment() { return !default(bool); }
}
To test the code we can use below,
static void Main(string[] args)
{
    ServiceFactory.CreateServiceProxyOne().ProcessRequest("Service Proxy one test.");
    ServiceFactory.CreateServiceProxyTwo().ProcessRequest("Service Proxy two test.");
} 
thanks mohammad.

 Few C# and Application Design books from Amazon,

2 comments: