【发布时间】:2018-02-01 06:11:48
【问题描述】:
我要问的部分与设计模式有关。
假设我有一个 IDrawing 界面。 另外两个名为 TextDrawing 和 ShapeDrawing 的基本类实现了这一点,我有一个知道如何绘制它们的 View 类!
但我有更复杂的绘图类,它们也实现了 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() 方法的建议。 View 中的 Draw 方法依赖于外部库进行绘制(在我的例子中,它是 SkiaSharp 库)。如果我在这些类中实现 Draw,它们将不再是通用的!例如,我将无法在其他项目中使用它们,因为我有不同的策略来绘制这些东西。
【问题讨论】:
-
阅读策略模式,并研究颠倒绘图的责任。
-
向你的界面添加一个绘图方法,让每个类自己处理绘图。
-
@Nkosi 你能看看我的更新吗?
-
@Nkosi 我现在明白了!这太强大了!
-
@Vahid 很高兴你知道了。请记住,强大的力量伴随着巨大的责任。负责任地使用这种力量。
标签: c# inheritance design-patterns interface composition