我在 C# 中有这个构建器(当然,示例被简化了):
class BusBuilder
{
Wheels mWheels = DefaultWheels;
int mRoute = 0;
public BusBuilder WithWheels(Wheels aWheels)
{
mWheels = aWheels;
return this;
}
public BusBuilder WithRoute(int aRoute)
{
mRoute = aRoute;
return this;
}
public Bus Build()
{
return new Bus { Wheels = mWheels, Route = mRoute };
}
}
它是这样使用的:
Bus bus =
new BusBuilder()
.WithWheels(someWheels)
.WithRoute(50)
.Build()
现在我想提取一个只包含一些方法的超类:
class VehicleBuilder
{
Wheels mWheels = DefaultWheels;
public VehicleBuilder WithWheels(Wheels aWheels)
{
mWheels = aWheels;
return this;
}
}
class BusBuilder : VehicleBuilder
{
...
}
问题是现在我不能写
Bus bus =
new BusBuilder()
.WithWheels(someWheels)
.WithRoute(50)
.Build()
因为WithWheels
返回 aVehicleBuilder
而不是 a BusBuilder
,因此没有定义WithRoute
方法。
你会怎么设计这个?