Factory Design Pattern

I try not to get too wrapped up in design patterns, because one can really overuse them, or use them in inappropriate places, if one is not careful; that's not to say that design patterns don't have their place, because I think design patterns are common ways programmers have found to "best practice" object oriented programming.

But even though I try not to over-emphasize design patterns, there are several design patterns that I find myself using over-and-over again. One such pattern is the factory pattern.

Factory patterns are often used with inheritance or interfaces, because one of the best uses of a factory design pattern is for figuring out what the best version of object is to instantiate, based on some input.

A factory pattern is basically an object that has some method that is a big if-statement (or switch statement, if one prefers). For instance, suppose your configuration file had a configuration for what type of data access you want to use (MSSQL, XML, Oracle, mySQL, etc).

Here's a simple example. The classes (along with accompanying interface) would look something like this:

interface IAccessLayer
{
    string GetQueryResultsAsString(string query);
   DataTable GetQueryResultsAsDataTable(string query);
   void ExecuteModificationQuery(string query);
}

Implementing classes might look something like this:

class MSSQLAccessLayer : IAccessLayer
{
   ///Implement public contract from IAccessLayer
}

class mySQLAccessLayer : IAccessLayer
{
   ///Implement public contract from IAccessLayer
}

class XMLAccessLayer : IAccessLayer
{
   ///Implement public contract from IAccessLayer
}

class OracleAccessLayer : IAccessLayer
{
   ///Implement public contract from IAccessLayer
}

If the configuration file had a finite set of allowable strings for the access layer that were as follows:

MSSQL
ORACLE
XML
MYSQL

Then, the factory method would look something like this:


public IAccessLayer GetAccessLayer(string dataAccessMedium)
{
   dataAccessMedium = dataAccessMedium.ToUpper();
   if(dataAccessMedium == "MSSQL")
   {
      return new MSSQLAccessLayer();
   }

   else if(dataAccessMedium == "ORACLE")
   {
      return new OracleAccessLayer();
   }

   else if(dataAccessMedium == "MYSQL")
   {
      return new mySQLAccessLayer();
   }
   else if(dataAccessMedium == "XML")
   {
      return new XMLAccessLayer();
   }
   else
   {
      throw new Exception("Error. " + dataAccessMedium + " is not a valid data access method");
   }
}


The above is one application of the factory pattern. There are lots of variants, and lots of applications, which is why I felt so inclined to write about them.

By the way, check out my new project at SourceForge: TestAutomation. It helps to automate software testing in Windows environments. https://sourceforge.net/projects/testautomation/ . I'm always looking for people to join the project.