我有一个名为
我不确定如何在
IDrawing
的接口,以及两个实现该接口的类TextDrawing
和ShapeDrawing
。我还有更复杂的绘图类,它们也实现了IDrawing
接口,但是由多个其他IDrawing
类组成。我不确定如何在
View
类中绘制这些复杂的类。我不想让View
类学习如何绘制每个新的IDrawing
类,因为这不是一个好的设计。我还有哪些其他选项?我的设计是否不正确?如果是,那么如何告诉View
的Draw
方法知道复杂类的基本部分并将它们绘制出来?下面是我的代码: public interface IDrawing
{
}
public class TextDrawing : IDrawing
{
}
public class ShapeDrawing : IDrawing
{
}
public class SignDrawing : IDrawing
{
public TextDrawing Text { get; set; }
public ShapeDrawing Border { get; set; }
}
public class MoreComplexDrawing : IDrawing
{
public TextDrawing Text { get; set; }
public ShapeDrawing Border1 { get; set; }
public ShapeDrawing Border2 { get; set; }
}
public class View
{
public void Draw(IDrawing drawing)
{
// The View only knows how to draw TextDrawing and ShapeDrawing.
// These as the primitive building blocks of all drawings.
// How can it draw the more complex ones!
if (drawing is TextDrawing)
{
// draw it
}
else if (drawing is ShapeDrawing)
{
// draw it
}
else
{
// extract the drawings primitive parts (TextDrawing and ShapeDrawing) and draw them!
}
}
}
更新:
我收到建议,建议在我的绘图类中实现Draw()
方法,但如果我这样做,它们将不再是通用的。例如,在我有不同的绘图策略的其他项目中将无法使用它们。有没有办法使我的设计更灵活,并保持其通用性?