gpt4 book ai didi

java - 具有泛型的构建器

转载 作者:行者123 更新时间:2023-11-30 05:24:36 24 4
gpt4 key购买 nike

我有以下层次结构

名为的双泛型类

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的Supplier,比如说DummySupplier

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

我想要一个ServiceBuilder<SomeObject, T>利用该供应商,有效地修复 T这样我只需要一个Function<SomeObject, U> mapper和一个 Consumer<U> consumer>构建我的服务。

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

是否有一些已知的模式可供采用?

最佳答案

都不是Function<SomeObject, U> mapper也不SomeObject知道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;
}
}

关于java - 具有泛型的构建器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58915679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com