我正在尝试创建一个使用相同基类(或接口)但具体工厂需要不同参数集的类的工厂。如果觉得我做错了什么,因为这些不同的枚举需要额外的代码。这能做得更好吗?要创建具有不同参数的工厂模式实现
类:
public interface IShapeData {}
public abstract class ShapeDataWithCorners : IShapeData
{
public double Width { get; set; }
}
class Square : ShapeDataWithCorners {}
class Rectangle : ShapeDataWithCorners
{
public double Height { get; set; }
}
class Circle : IShapeData
{
public double Radius { get; set; }
}
class Oval : IShapeData
{
public double Radius1 { get; set; }
public double Radius2 { get; set; }
}
工厂:
public enum RoundShapeTypes
{
Circle,
Oval
}
public enum CornerShapeTypes
{
Square,
Rectangle
}
public class RoundShapeDataFactory : IShapeDataFactory
{
private readonly RoundShapeTypes m_shapeType;
public RoundShapeDataFactory (RoundShapeTypes shapeType)
{
m_shapeType = shapeType;
}
public IShapeData CreateShapeData()
{
switch (m_shapeType)
{
case RoundShapeTypes.Circle:
return new Circle();
case RoundShapeTypes.Oval:
return new Oval();
}
}
}
public class CornerShapeDataFactory : IShapeDataFactory
{
private readonly CornerShapeTypes m_shapeType;
public CornerShapeDataFactory (CornerShapeTypes shapeType)
{
m_shapeType = shapeType;
}
public IShapeData CreateShapeData()
{
switch (m_shapeType)
{
case CornerShapeTypes.Square:
return new Square();
case CornerShapeTypes.Rectangle:
return new Rectangle();
}
}
}
类调用工厂:
public class RoundShapeManager
{
public IShapeData CurrentShapeData{get; set; }
public void SetShapeType (RoundShapeTypes shapeType)
{
RoundShapeDataFactory factory = new RoundShapeDataFactory (shapeType);
CurrentShapeData = factory.CreateShapeData();
}
}
public class CornerShapeManager
{
public IShapeData CurrentShapeData {get; set; }
public void SetShapeType (CornerShapeTypes shapeType)
{
CornerShapeDataFactory factory = new CornerShapeDataFactory (shapeType);
CurrentShapeData = factory.CreateShapeData();
}
}
这些 “经理人” 实际上是WPF的ViewModels,将可以改变他们的代表在运行时显示数据。为了简洁,我删除了viewmodel特定的代码。
这可能是一个很好的问题[codereview.se] – null
我刚刚离开了评论,而不是近距离投票。由于近距离投票是“太宽泛”,我想这是因为你的问题是开放式的,这对CR是有效的,而不是在SO上(见你链接到的元问题的接受答案中的表格)。在与您所引用的行相同的段落中:“*相反,投票结束时间过长或主要以意见为基础。*” – null