I’d like to know if I follow the right path, because I feel that the following code is wrong. Sorry, I didn’t know how to name properly this question.
I have a certain ShapeEntity class that is used for loading data from DB. There are other concrete classes for Shape (I can have many of them in the future) so I want to employ LSP to draw these shapes, that’s why I use IShape abstraction. I instantiate concrete shape objects by using DB info which is provided by ShapeEntity.
So my concern lies inside Main() function where I create these Shapes just using simple if-else. Is this correct approach to create “unknown” objects using if-else block? Maybe I could carry out creation of Shape objects to some kind of ShapeService? How could it be solved the other way?
public class ShapeEntity
{
int idShape { get; set; }
}
public interface IShape
{
void Draw();
}
public class Square : IShape
{
public void Draw() { }
}
public class Rectangle : IShape
{
public void Draw() { }
}
public class Canvas()
{
public static void Main()
{
List<IShape> Shapes = new List<IShape>();
foreach(ShapeEntity ShapeItem in ShapeRepository.GetAll())
{
if(ShapeItem.idShape == 1)
{
Shapes.Add(new Square());
}
else if(ShapeItem.idShape == 2)
{
Shapes.Add(new Rectangle());
}
}
}
public void DrawShapesOnCanvas(IList<IShape> Shapes)
{
foreach(IShape Shape in Shapes)
{
Shape.Draw();
}
}
}
You should consider using
Factorypattern and instead usingIdyou should useenumExample: