Chris's coding blog

C# Design Patterns: the Factory pattern

December 03, 2008

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()
{
r eturn "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();
}
}
}
view raw gistfile1.cs hosted with ❤ by GitHub

csharpdesign-patterns

I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via GithubStackoverflowResume