4

我在 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方法。

你会怎么设计这个?

4

1 回答 1

14

当涉及到继承时,构建器模式有点让人头疼。你可以这样做:

class VehicleBuilder<T> where T : VehicleBuilder<T>
{
    private T @this;

    protected VehicleBuilder()
    {
        // Or pass it in as a constructor parameter
        @this = (T) this;
    }

    public T WithWheels(...)
    {
        return @this;
    }
}

然后:

class BusBuilder : VehicleBuilder<BusBuilder>
{
    ...
}

那时,您的WithWheels方法仍将返回 a BusBuilder,因此您仍然可以调用WithRoute.

您还需要Build在每个派生类构建器中使用一个新方法,请注意...

于 2012-12-19T10:16:55.090 回答