已更新我已更新示例以更好地说明我的问题。我意识到它遗漏了一个特定点 - 即该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 需要该值的事实,否则它只会被赋予空字符串。
实现此方案的正确方法是什么?