I have different fruit class, all implements the same interface IFruit :
public interface IApple : IFruit{ }
public interface IBanana : IFruit{ }
public interface ICarrot: IFruit{ }
Each of them have their own drawer :
public class AppleDrawer
{
public void Draw(IApple apple, Graphics graphics){}
}
public class BananaDrawer
{
public void Draw(IBanana banana, Graphics graphics){}
}
If I want to draw a list of fruit, I am doing the following
public void DrawFruits(List<IFruit> fruits, Graphics graphics)
{
foreach(var fruit in fruits)
{
if(fruit is IBanana)
{
var banana = (IBanana)fruit;
var drawer = new BananaDrawer();
drawer.Draw(banana, graphics);
}
else if(fruit is IApple)
{
var apple = (IApple)fruit;
var drawer = new AppleDrawer();
drawer.Draw(banana, graphics);
}
etc...
}
I feel extremely dirty when I read my code.
My problem is the multiple if..else statement, because I have 12 differents fruits, and I have to do this statement a lot in my current project.
Is there a way to refactoring my DrawFruits method ?
I am thinking of a kind of factory pattern but I don’t really see how to do it.
Is my fruit class must take a Drawer as a Property ? Or maybe I can call a Drawer Factory method ?
This is a pattern that I find a lot in my current project, and I don’t find a solution that satisfies me.
One way is to have a
GetDraweron yourIFruitand a
BaseDrawerinterfaceNow your draw Fruits is simply
Sometimes you need a
Drawer,PlotterandPrinterso yourIFruitmight get too heavy like belowVisitor pattern is a good solution for this. Basically you will have
only one class for all possible drawing visits
Here you just have one
DrawVisitorinstead ofAppleDrawer,BananaDraweretc and all your draw code is neatly in one place. You might end up needingPlotterVisitor,PrinterVisiteretc