更新私の問題をよりよく説明するために、例を更新しました。特定のポイントが 1 つ欠けていることに気付きました。つまり、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 には値が必要であるという事実を強制したいと考えています。そうしないと、空の文字列しか与えられません。
このシナリオを実装する正しい方法は何ですか?