Please navigate to the bottom of the page for Table of Contents

Saturday, May 21, 2011

Simple Patterns: Factory Pattern

Sometimes, when creating an object it’s more complicated than just calling a constructor.  Maybe there is logic that needs to be processed to determine which specific class needs to be returned. Ideally you don’t want to have this logic duplicated throughout your application in case it ever changes. It’s much easier to maintain this logic if it is kept in a single location. One way to do this is to follow the factory pattern.

The idea behind the factory pattern is that you call into a common method to create an instance of a common object.  Here is a simple but practical example.

public static class LogFactory
{
// common method that determines which ILog to use
public static ILog GetLog()
{
#if DEBUG
return new LogConsole();
#endif

if (string.Equals(ConfigurationManager.AppSettings["UseSQLLog"], "1"))
{
return new LogSQL();
}
else
{
return new LogFile();
}
}
}

public interface ILog
{
void WriteLog(string entry);
}

public class LogFile : ILog
{
public void WriteLog(string entry)
{
// write entry to file
}
}

public class LogSQL : ILog
{
public void WriteLog(string entry)
{
// write entry to SQL
}
}

public class LogConsole : ILog
{
public void WriteLog(string entry)
{
Console.WriteLine(entry);
}
}


No comments:

Post a Comment