Factory pattern with reflection (C#)

Today I thought about implementing the factory pattern on a base class with five derived classes. I started with a basic switch-case statement but after a few lines I noticed the redundancy: case “x” instantiate X, case “y” instantiate Y, etc. I wondered what it would look like done with reflection and here’s the result (in a simplified example):

Code Snippet
public interface Shape
{
    void Draw();
}

public class Square : Shape
{
    public void Draw()
    {
        Console.WriteLine(" _ \n|_|");
    }
}

public class Circle : Shape
{
    public void Draw()
    {
        Console.WriteLine("O");
    }
}

public static class ShapeFactory
{
    public static Shape GetShape(string shapeName)
    {
        Assembly currentAssembly = Assembly.GetExecutingAssembly();
        var currentType = currentAssembly.GetTypes().SingleOrDefault(t => t.Name == shapeName);
        return (Shape)Activator.CreateInstance(currentType);
    }
}

There are a two advantages in this approach:
1. The code is shorter.
2. The code doesn’t require a change even if we add new classes that derive shape.

About these ads

3 Responses to “Factory pattern with reflection (C#)”

  1. Bala Sakthis Says:

    Hi Tom, Very short and crisp. Thanks! for sharing.

    — Bala

  2. Anil Bhatia Says:

    Hi Tom, Thats a nice one!! but it assumes that all my classes are in the executing assembly. what if my classes are in different assemblies??

    • techtaunt Says:

      Hello Anil, great question :)

      Assuming the dll you’re mentioning is loaded you could extend the solution to search all loaded assemblies:

      var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();

      You could then iterate over them until you find the type you’ve specified.

      Hope I answered your question. :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: