我正在构建一个大致像这样工作的流畅 API(假设存在一个返回 a 的Person带有 getter的类):getIdLong
String result = context.map(Person::getId)
.pipe(Object::toString)
.pipe(String::toUpperCase)
.end(Function.identity())
如您所见,只有.end-function 充当终端运算符。这使上述 API 的整体使用.end(Function.identity())变得混乱,因为即使前面的.pipe-call 已经具有正确的类型,我也经常不得不以 -call 结束。
有什么方法可以制作一个 fluent-API,使其一部分既是终端操作员又是“桥接操作员”?我只是不想用专门的 pipe变体pipeTo(例如,只接受 aFunction<CurrentType, ExpectedType>和内部调用的管道.end)来模拟所述行为,因为它迫使用户考虑 API 的一个非常特定的部分,这对我来说似乎是不必要的。
编辑:根据要求简化上下文实现:
class Context<InType, CurrentType, TargetType> {
private final Function<InType, CurrentType> getter;
public Context(Function<InType, CurrentType> getter) {
this.getter = getter;
}
public <IntermediateType> Context<InType, IntermediateType, TargetType>
pipe(Function<CurrentType, IntermediateType> mapper) {
return new Context<>(getter.andThen(mapper));
}
public Function<InType, TargetType> end(Function<CurrentType, TargetType> mapper) {
return getter.andThen(mapper);
}
}
//usage
Function<Person, String> mapper = new Context<Person, Long, String>(Person::getId)
.pipe(Object::toString)
.pipe(String::toUpperCase)
.end(Function.identity());
mapper.apply(new Person(...))
慕斯709654
慕尼黑的夜晚无繁华
陪伴而非守候
相关分类