I have an interface and 3 function
public interface IDrawingObject
{
void Draw(Color c);
}
public class DrawTriangle : IDrawingObject
{
public void Draw(Color c)
{
//for demo purpose
Console.WriteLine("Drawing Triangle with color " + c.Name );
}
}
public class DrawCircle : IDrawingObject
{
public void Draw(Color c)
{
//for demo purpose
Console.WriteLine("Drawing Circle with color " + c.Name);
}
}
public class DrawRectangle : IDrawingObject
{
public void Draw(Color c)
{
//for demo purpose
Console.WriteLine("Drawing Rectangle with color " + c.Name);
}
}
and this enum
public enum Shapes
{
Circle,
Rectangle,
Triangle
}
and here can be a lot more function(and enums)
I want to have static void Draw(Shapes s, Color c)
that selects the right function to call based on this enum, and it looks to me that using if-else(or switch will bloat the code)
So i took another approach which is to use a IDictionary
private static IDictionary<Shapes, Action<Color>> Mapper = new Dictionary<Shapes, Action<Color>>
{
{ Shapes.Circle, (Color c) => { IDrawingObject draw = new DrawTriangle(); draw.Draw(c);} },
{ Shapes.Rectangle, (Color c) => { IDrawingObject draw = new DrawRectangle(); draw.Draw(c); } },
{ Shapes.Triangle, (Color c) => { IDrawingObject draw = new DrawCircle(); draw.Draw(c); } }
};
and my function is
public static void Draw(Shapes s, Color c)
{
if (Mapper.ContainsKey(s))
{
Mapper[s](c);
}
}
but still, it looks to me that I'm still doing a lot of unscary copy and paste
Is there any better way to do it?
P.S