【发布时间】:2020-06-03 12:57:28
【问题描述】:
目前,我们有一个依赖于标准 .NET XML 序列化/反序列化机制的 .NET 应用程序。例子虽然简化了,但意思是一样的。
public abstract class Shape
{
[XmlAttribute("id")]
public string Id { get; set; }
[XmlAttribute("level")]
public int Level { get; set; }
public abstract void Draw();
public abstract void Clear();
public abstract void Scale(double scale);
}
[XmlType("Circle")]
public class Circle : Shape
{
public double Radius { get; set; }
public override void Draw() {}
public override void Clear() {}
public override void Scale(double scale) {}
}
[XmlType("Rectangle")]
public class Rectangle: Shape
{
public double Height { get; set; }
public double Width { get; set; }
public override void Draw() {}
public override void Clear() {}
public override void Scale(double scale) {}
}
public class Picture
{
public double Scale { get; set; }
[XmlArrayAttribute("Shapes")]
public Collection<Shape> Shapes { get; set; }
public void Setup()
{
foreach (Shape shape in Shapes)
{
shape.Draw();
}
foreach (Shape shape in Shapes)
{
shape.Scale(Scale);
}
}
public void Cleanup()
{
foreach (Shape shape in Shapes)
{
shape.Clear();
}
}
public static Picture FromXml(XmlReader xmlReader)
{
XmlSerializer serializer = new XmlSerializer(typeof(Picture));
return serializer.Deserialize(xmlReader) as Picture;
}
}
例如,输入的 XML 文件将如下所示:
<Picture>
<Scale>0.9</Scale>
<Shapes>
<Circle id="1">
<Radius>1.5</Radius>
</Circle>
<Circle id="2">
<Radius>3</Radius>
</Circle>
<Rectangle id="3">
<Height>300</Height>
<Width>300</Width>
</Rectangle>
</Shapes>
</Picture>
但模型类包含一个逻辑(Draw()、Clear() 和 Scale() 方法),它似乎违反了单一责任原则。因此我们不知道将逻辑分成几个类是否有意义?
如果是,那么如何?因为一旦我们读取 XML 文件,所有对象都只能作为 Shape 对象访问,因此我们必须在将 if 传递给处理程序类之前或在该方法内部显式转换对象,例如:
public abstract class Drawer
{
public abstract void Draw(Shape shape);
}
public class CircleDrawer : Drawer
{
public override void Draw(Shape shape)
{
Circle circle = shape as Circle;
if (circle == null)
{
throw new ArgumentException("Passed object is not of type Circle");
}
}
}
如果该问题已知,请将我重定向到该资源。
提前谢谢你。
【问题讨论】:
-
您不需要进行强制转换,即
shape as Circle。因为Circle是一个Shape,将其视为Shape非常高兴,但由于Circle覆盖了Draw方法,被覆盖的方法就是被调用的方法.考虑以下...dotnetfiddle.net/YQxhph -
从:Draw(Shape shape) 更改为:Draw(Circle shape)
标签: c# .net oop design-patterns xml-serialization