Top

Tags


Roadkill .NET Wiki

Google ads

Recommended reading


Search

Wednesday
Dec032008

C# Design Patterns: the Factory pattern

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

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
« C# Design Patterns: the Abstract Factory Pattern | Main | Whois, DNS, CName, MX record lookup in C# »