我正在嘗試創建一個使用相同基類(或接口)但具體工廠需要不同參數集的類的工廠。如果覺得我做錯了什麼,因爲這些不同的枚舉需要額外的代碼。這能做得更好嗎?要創建具有不同參數的工廠模式實現
類:
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