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

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 )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: