作为另一个班级的公共班级成员,我从一个建筑商模式中获得了很大的吸引力:
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的受保护构造函数。如何让构建器与零件的后代一起工作,并获得相同的必备构建器语义?