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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via Github, Stackoverflow, Resume