Wednesday
Dec032008
C# Design Patterns: the Factory pattern
Wednesday, December 3, 2008 at 10:59PM Summary
One class (the factory) creates instances of other classes which all implement the same interface or subclass a specific class. The factory optionally calls the method(s) of the instance it creates.
Example usage
Plugin architecture (implemented alongside reflective loading of types) is one good usage of the Factory design pattern.
namespace DesignPatterns
{
/// <summary>
/// Defines the methods/properties the plugin can support.
/// </summary>
public interface IPlugin
{
string GetDetails();
}
/// <summary>
/// A plugin for Gifs.
/// </summary>
public class GifHandler : IPlugin
{
public string GetDetails()
{
return "I'm a plugin for .GIF filetypes";
}
}
/// <summary>
/// A plugin for jpgs.
/// </summary>
public class JpgHandler : IPlugin
{
public string GetDetails()
{
return "I'm a plugin for .JPG filetypes.";
}
}
/// <summary>
/// The class to handle extensions with.
/// </summary>
public class PluginFactory
{
public string ShowFileDetails(string extension)
{
IPlugin plugin = null;
switch (extension)
{
case "gif":
plugin = new GifHandler();
break;
case "jpg":
plugin = new JpgHandler();
break;
default:
throw new NotSupportedException(string.Format("{0} is not supported.", extension));
}
return plugin.GetDetails();
}
}
}






Reader Comments