LSP:条件创建对象

des*_*man 1 c# oop

我想知道我是否遵循正确的道路,因为我觉得以下代码是错误的.对不起,我不知道如何正确地命名这个问题.

我有一个ShapeEntity类,用于从DB加载数据.Shape还有其他具体的类(我将来可能会有很多类)所以我想用LSP来绘制这些形状,这就是我使用IShape抽象的原因.我通过使用ShapeEntity提供的DB信息来实例化具体的形状对象.

所以我关注的是Main()函数,我只使用简单的if-else创建了这些Shapes.这是使用if-else块创建"未知"对象的正确方法吗?也许我可以将Shape对象创建为某种ShapeService?怎么能以其他方式解决?

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Emb*_*rja 5

你应该考虑使用Factory模式而不是使用Id你应该使用enum

例:

 public class ShapeFactory
    {
        public static IShape GetShape(ShapeType shapeType)
        {
            switch (shapeType)
            {
                case ShapeType.Square:
                    return new Square();

                case ShapeType.Rectangle:
                    return new Rectangle();
                default:
                    break;
            }

            return null;
        }
    }

    public enum ShapeType
    {
        Square,
        Rectangle
    }
Run Code Online (Sandbox Code Playgroud)