我有以下层次结构

一个双重通用类,名为

public class Service<T, U>
{
    private final Supplier<T>
    private final Function<T, U>
    private final Consumer<U>
    // more fields and methods ...
}


该类ServiceBuilder<T, U>的构建器,具有用于构建器的常用流利API

public class ServiceBuilder<T, U>
{
    private Supplier<T> supplier;
    private Function<T, U> mapper;
    private Consumer<U> consumer;
    // more fields and methods ....

    public ServiceBuilder<T, U> withSupplier(Supplier<T> supplier)
    {
        this.supplier = supplier;
        return this;
    }

    // more fields and methods ....

    public Service<T, U> build()
    {
        return new Service(supplier, mapper, consumer);
    }
}


基于此,我想提供一个易于使用的T供应商,比如说DummySupplier

public class DummySupplier implements Supplier<SomeObject>
{
    public SomeObject get()
    {
        return new SomeObject();
    }
}


我想要一个可以利用此供应商的ServiceBuilder<SomeObject, T>,可以有效地修复T,以便只需要一个Function<SomeObject, U> mapperConsumer<U> consumer>即可构建我的服务。

我该如何处理?扩展ServiceBuilder不起作用,因为我想重用的所有现有方法都返回ServiceBuilder,而不是某些扩展ServiceBuilder的类...

是否有一些已知的方法可以解决?

最佳答案

Function<SomeObject, U> mapperSomeObject都不知道DummySupplier
此信息必须放在某个地方,例如在SpecializedServiceBuilder中:

public class SpecializedServiceBuilder<U> extends ServiceBuilder<SomeObject, U> {

    ServiceBuilder withSomeObjectFunction(Function<SomeObject, U> mapper) {
        this.supplier = new DummySupplier();
        this.mapper = mapper;
        return this;
    }
}

10-05 21:48