作为另一个类的公共类成员,我从构建器模式中获得了很大的吸引力:
public class Part
{
public class Builder
{
public string Name { get; set; }
public int Type { get; set; }
public Part Build()
{
return new Part(Name, Type);
}
}
protected Part(string name, int type)
{
...
}
}
注意受保护的构造函数 - 我喜欢我必须使用生成器来获取零件的方式。来电
Part p = new Part.Builder() { Name = "one", Type = 1 }.Build();
工作得很好。我想做的是使用这个构建器来提供基于类型的特殊部件(例如):
public class SpecialPart : Part
{
protected SpecialPart(string name, int type) : base(name, type) { }
}
并对构建器进行了轻微更改:
public Part Build()
{
if (Type == _some_number_)
return new SpecialPart(Name, Type);
return new Part(Name, Type);
}
但这不起作用 - Part.Builder 看不到 SpecialPart 的受保护构造函数。如何让 Builder 使用 Part 的后代并获得相同的 must-have-a-builder 语义?