C# 取决于对象类型的创作模式
在我的winform项目中,我有一些图形模型类:C# 取决于对象类型的创作模式,c#,design-patterns,C#,Design Patterns,在我的winform项目中,我有一些图形模型类:Rectangle、Association line和Text。 例如: public class Rectangle { public short Id { get; set; } public short Zindex { get; set; } public Color BackColor { get; set; } public bool Selected { get; set; } public
Rectangle
、Association line
和Text
。
例如:
public class Rectangle
{
public short Id { get; set; }
public short Zindex { get; set; }
public Color BackColor { get; set; }
public bool Selected { get; set; }
public Size Size{ get; set; }
}
和通用IntefaceIPathBuilder
,以及为每个模型生成图形路径的类:RectangleGraphicPathBuilder
,等等。示例:
public class RectangleGraphicPathBuilder : IPathBuilder
{
protected override GraphicsPath Build(IShape inShape )
{
var shape = inShape as Rectangle;
var newPath = new GraphicsPath();
newPath.AddRectangle(new Rectangle(shape.Location.X, shape.Location.Y, shape.Size.Width, shape.Size.Height));
return newPath;
}
}
我需要使用一些模式在集合中的形状迭代时调用这些构建器。比如:
forech(IShape shape in shapeColection){
var path = IPathBuilder.Builder(shape);
}
我很乐意提供有关它的任何提示。向
IShape
界面添加一个方法AddShapeToPath
,该界面将专门针对每个形状。在生成器中调用此方法,而不是尝试处理每种形状类型
public interface IShape {
void AddShapeToPath(GraphicsPath path);
}
public class Rectangle: IShape
{
// properties removed for readability
public void AddShapeToPath(GraphicsPath path)
{
path.AddRectangle(new Rectangle(Location.X, Location.Y, Size.Width, Size.Height));
}
}
protected override GraphicsPath Build(IShape inShape )
{
var newPath = new GraphicsPath();
inShape.AddShapeToPath(newPath);
return newPath;
}
我认为你需要策略设计模式。Samy已经提供了策略设计模式实现的示例 这看起来像是复制对象,而不是构建新对象。。。在IShape中放置一个复制或克隆方法,并让每个类以各自特定的方式实现它,怎么样?您的意思是在模型中添加PathGenerator方法?我假设该模型仅包含其参数:颜色、大小等,以及我希望为特定服务IPathBuilder提供的bild图形路径功能。我假设该模型仅包含其参数:颜色、大小、,以及我希望为特定服务IPathBuilder提供的bild图形路径的能力。该形状只包含其自身构建所需的数据。如果需要在形状本身中构建路径,那么只需在接口中添加一个方法,以便在需要区分形状时提供路径