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):
{
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.