Design Patterns Series 4 - Factory Pattern

Previous post explored decorator pattern that take care of flows in standard OOP especially when it comes to inheritance, also this post will explore another pattern that serve the same concept.

Factory Pattern :
the factory design pattern lets you improve the new operator by giving you a lot more flexibility when you create new object. When you use this pattern, you use your own code to create new objects, you don't use just the new  operator.

To know how we can improve the new  operator consider you want to create a connection to MSSQL database, you will create it using the following line 
Connection conn = new SQLConnection();
and when we want to connect to Oracle database we will use the following connection
Connection conn = new OracleConnection();
but we want to make the default datebase is MySql so we need the next connection
Connection conn = new MySqlConnection();
of course we will use one connection so we will choose the right connection according to database type by writing method that return the desired connection object.
public Connection CreateConnection(String type)
{
   if(type == "sql server")
   {
      return new SqlConnection();
   }
   else if(type == "oracle")
   {
      return new OracleConnection();
   }
   else
   {
      return new MySqlConnection();
   }
}
now if we want to create factory pattern that will encapsulate the CreateConnection() method into ConnectionFactory class with constructor that receive the type of desired connection.
public class ConnectionFactory
{
   protected String type;
   public ConnectionFactory(String t)
   {
      type = t;
   }
   public Connection CreateConnection()
   {
      if(type == "sql server")
      {
         return new SqlConnection();
      }
      else if(type == "oracle")
      {
         return new OracleConnection();
      }
      else
      {
         return new MySqlConnection();
      }
   }
}
we will create the connection object and use it as follows
FactoryConnection factory = new FactoryConnection("oracle");
Connection conn = factory.CreateConnection();

conn.UserName = "Miro";
conn.Password = "Miro";
conn.Open();
notice after we created connection object we used it extensively. To be able to use the same code for all connection types, the code should be polymorphic(all connection object should share the same interface or be derived from the same base class).
public abstract class Connection
{
   public abstract String Description();
}
now let us create the various connection types
public class SqlConnection : Connection
{
   public SqlConnection()
   {
   }
   public override String Description() 
   {
      return "sql server";
   }
}
public class OracleConnection : Connection
{
   public OracleConnection()
   {
   }
   public override String Description() 
   {
      return "Oracle";
   }
}
To check if your factory is running correctly try the following code fragment
ConnectionFactory factory = new ConnectionFactory("oracle");
Connection conn = factory.CreateConnection();
Console.WriteLine("Now you connect to " + conn.Description());
this code fragment will print out
Now you connect to oracle

Another Factory Pattern Technique :
Now we will explore another technique to build the factory pattern. The Factory method design pattern should define an interface for creating an object, but let the derived class decide which class to instantiate.Factory method lets a class defer instantiation to subclasses.

Our code sample didn't let the subclass decide which class to instantiate, it simply inherit from it and override it. The another approach means you define how factory methods should work and leave it up to subclasses to implement the actual factory(delegating control to subclasses).

Now we will modify the ConnectionFactory class to build the new technique.
public abstract class ConnectionFactory
{
   public abstract Connection CreateConnection(String type);
}
To gain more control over object creation process, your factory connection class should inherit ConnectionFactory and implement CreateConnection method
public class MyConnectionFactory : ConnectionFactory
{
    public override Connection CreateConnection(String type)
    {
        if(type == "sql server")
      {
         return new SqlConnection();
      }
      else if(type == "oracle")
      {
         return new OracleConnection();
      }
      else
      {
         return new MySqlConnection();
      }
    }
}
That is all except one thing, instead creating object from ConnectionFactory, you will create object from MyConnectionFactory. To test the new technique try the following code fragment
MyConnectionFactory myfactory = new MyConnectionFactory();
Connection conn = myfactory.CreateConnection("oracle");
Console.Write("Now you connect to " + conn.Description());
this code fragment will print out
Now you connect to oracle
The result as you have got before but now you implemented your own version of your factory. You set the factory specification by creating an abstract class or interface that subclasses have to use. No longer does a single concrete factory object instantiate your objects a set of subclasses does the work.

you can download the full source code here

Comments

  1. thanks for this information .
    you can find factory design pattern in simple and easy to understand language in a detail on
    http://www.itsoftpoint.com/?page_id=2666

    ReplyDelete

Post a Comment

Popular posts from this blog

Android : How to change progress bar color at runtime programmatically?

ASP.Net MVC : Conditional Validation using ValidationAttribute

How to fire RowCommand event of nested GridView?