更新 我更新了示例以更好地说明我的问题。我意识到它遗漏了一个特定点 - 即 CreateLabel()
方法始终采用标签类型这一事实,因此工厂可以决定要创建的标签类型。问题是,它可能需要获取更多或更少的信息,具体取决于它要返回的标签类型。
我有一个工厂类,它返回表示要发送到打印机的标签的对象。
工厂类如下所示:
public class LargeLabel : ILabel
{
public string TrackingReference { get; private set; }
public LargeLabel(string trackingReference)
{
TrackingReference = trackingReference;
}
}
public class SmallLabel : ILabel
{
public string TrackingReference { get; private set; }
public SmallLabel(string trackingReference)
{
TrackingReference = trackingReference;
}
}
public class LabelFactory
{
public ILabel CreateLabel(LabelType labelType, string trackingReference)
{
switch (labelType)
{
case LabelType.Small:
return new SmallLabel(trackingReference);
case LabelType.Large:
return new LargeLabel(trackingReference);
}
}
}
假设我创建了一个名为 CustomLabel 的新标签类型。我想从工厂退回这个,但它需要一些额外的数据:
public class CustomLabel : ILabel
{
public string TrackingReference { get; private set; }
public string CustomText { get; private set; }
public CustomLabel(string trackingReference, string customText)
{
TrackingReference = trackingReference;
CustomText = customText;
}
}
这意味着我的工厂方法必须改变:
public class LabelFactory
{
public ILabel CreateLabel(LabelType labelType, string trackingReference, string customText)
{
switch (labelType)
{
case LabelType.Small:
return new SmallLabel(trackingReference);
case LabelType.Large:
return new LargeLabel(trackingReference);
case LabelType.Custom:
return new CustomLabel(trackingReference, customText);
}
}
}
我不喜欢这样,因为工厂现在需要迎合最低公分母,但同时 CustomLabel 类需要获得自定义文本值。我可以提供额外的工厂方法作为覆盖,但我想强制执行 CustomLabel 需要该值的事实,否则它只会被赋予空字符串。
实现这个场景的正确方法是什么?
最佳答案
那么,你想如何调用工厂方法?
专注于您希望如何使用您的 API,实现通常会非常清楚。如果您将 API 的预期结果编写为单元测试,这会变得更加容易。
在这里重载很可能是正确的做法,但这实际上取决于您希望如何使用工厂。
关于c# - 工厂类知道的太多了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/698000/