October 22, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Implement Common Creational Design Patterns

  • July 7, 2004
  • By Mark Strawmyer
  • Send Email »
  • More Articles »

Factory Design Pattern

The factory design pattern involves having an interface definition for an object and having a class determine the actual creation of a concrete class. The controlling class determines which specific type of class is desired and creates it at runtime. This pattern can be very useful for things such as error logging within an application where the error can be logged to any number of locations (such as a database or file).

An interface dictates the behavior the loggers are to provide and creates a common set of method calls for logging information. All references to loggers within the calling objects would be typed as the logging interface. Rather than create a specific instance of a database or file logger when an error occurs, another controlling class determines which specific type to instantiate and returns it. This allows the logging type to be configurable within the application.

Factory Sample Code

The following sample C# code depicts how to implement the factory design pattern. It is important to note that I chose to use an abstract class for the Logger in place of an interface. The main difference is that using an abstract class allows me to include any additional methods within the Logger class that are common to all of the loggers. This is a technique I find very useful for isolating utility type methods applicable to only a specific type of object and its instances. An interface would not allow this same behavior:

using System;namespace CodeGuru.DesignPattern{   /// <summary>   /// Sample abstract class dictate iteration with the logging.   /// </summary>   public abstract class Logger   {      public abstract void LogError(Exception exception);      public abstract void LogError(string error);   }   /// <summary>   /// Sample class to contain database specific logging.   /// </summary>   public class DbLogger : Logger   {      public DbLogger()      {      }      public override void LogError(Exception exception)      {         // Db specific logging here ...      }      public override void LogError(string error)      {         // Db specific logging here ...      }   }   /// <summary>   /// Sample class to contain file specific logging.   /// </summary>   public class FileLogger : Logger   {      public FileLogger()      {      }      public override void LogError(Exception exception)      {         // File specific logging here ...      }      public override void LogError(string error)      {         // File specific logging here ...      }   }   /// <summary>   /// Control creation of concrete instances of Loggers.   /// </summary>   public class LogFactory   {      /// <summary>      /// Constructor to create the object from being instantiated.      /// </summary>      private LogFactory()      {      }      /// <summary>      /// Create a concrete instance of a logging class based on the input.      /// </summary>      /// <param name="logType">Type of logger to instantiate.</param>      /// <returns>Concreate instance of a Logger.</returns>      public static Logger GetLogger(int logType)      {         if( logType == 1 )         {            return new DbLogger();         }         else         {            return new FileLogger();         }      }   }   /// <summary>   /// Sample class to use a Logger to log a message.   /// </summary>   public class Log   {      private int _LogType;      /// <summary>Get or set the type of log to use.</summary>      public int LogType      {         get { return this._LogType; }         set         {            this._LogType = value;            this._Logger = LogFactory.GetLogger(value);         }      }      /// <summary>Logger instance to perform the logging.</summary>      private Logger _Logger;      /// <summary>      /// Constructor      /// </summary>      public Log()      {         this.LogType = 1;      }      /// <summary>      /// Log an exception.      /// </summary>      /// <param name="exception">Exception to log.</param>      public void LogError(Exception exception)      {         _Logger.LogError(exception);      }      /// <summary>      /// Log an error message.      /// </summary>      /// <param name="error">Error message to log.</param>      public void LogError(string error)      {         _Logger.LogError(error);      }    }}

A number of classes comprise this solution. The first is the abstract class that defines how you'll access your Logger. The next two classes, DbLogger and FileLogger, are very basic placeholder examples of where the database and file-specific logging (respectively) would be implemented. The fourth class is the LogFactory, which controls the instantiation of concrete instances of the desired Logger based on the requested type. The fifth and final class involved is the Log class, which is a logging controller of sorts. You configure this object as desired to control access to the underlying logging capabilities.

Possible Pattern Enhancements

You now have seen a few examples of creational design patterns, along with some examples of how you can apply them. This article touched on only the tip of the iceberg when it comes to design patterns. There are a couple of additional creational patterns, along with a host of other categories containing numerous design patterns of their own. Consider the following items pertaining to the patterns:

  • You can use the ASP.NET cache or application state to implement a singleton pattern as well. The GetInstance() method would check whether the appropriate cache or application setting location exists. If it was already loaded, it would pull from the source. Otherwise, it would load it. This isn't necessarily preferred over the pattern example, but rather an example of another way to implement it.
  • The factory example represents the log type to create (database or file) with an integer. The LogType property on the Log controls which type of Logger is created and utilized for the actual logging. This could just as easily be an enumerated type that represents all allowable types of loggers, or reflection could be used to create an instance of any type of Logger that inherits from the Logger base class.
  • Rather than have a specific number or enumeration to represent the logger in the factory design pattern, the desired logging configuration from an application configuration file could use the System.Configuration.ConfigurationSettings.AppSettings() method. This would allow you to dynamically choose which logger to use based on the application configuration and even call loggers contained within another assembly.

Future Columns

The topic of the next column is yet to be determined. If you have something in particular that you would like to see explained here, you could reach me at mstrawmyer@crowechizek.com.

About the Author

Mark Strawmyer (MCSD, MCSE, MCDBA) is a senior architect of .NET applications for large and mid-sized organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in architecture, design, and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C#. You can reach Mark at mstrawmyer@crowechizek.com.





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel