Java 8:使用andThen()和apply()方法时双函数的工作原理
目前,Java 8:使用andThen()和apply()方法时双函数的工作原理,java,builder,functional-interface,Java,Builder,Functional Interface,目前,BiFunction接口有两种方法和apply()。我在web上找到了不同的示例,但下面的示例是我无法理解的——“这些方法的链接是如何工作的” 示例1: BiFunction<String, String,String> bi = (x, y) -> { return x + y; }; Function<String,String> f = x-> x+" spinner
BiFunction
接口有两种方法和apply()
。我在web上找到了不同的示例,但下面的示例是我无法理解的——“这些方法的链接是如何工作的”
示例1:
BiFunction<String, String,String> bi = (x, y) -> {
return x + y;
};
Function<String,String> f = x-> x+" spinner";
System.out.println(bi.andThen(f).apply("hello", " world"));
这里,方法调用按顺序进行,首先初始化Builder
(静态)类,然后withOwner
分配所有者名称并返回Builder,然后分配分支名称并返回Builder,
下一个期初余额被给出并返回生成器,最后生成将返回BankAccount
实例。请参见银行账户
课程
public class BankAccount {
public static class Builder {
private long accountNumber;
private String owner;
private String branch;
private double balance;
public Builder(long accountNumber) {
this.accountNumber = accountNumber;
}
public Builder withOwner(String owner){
this.owner = owner;
return this;
}
public Builder atBranch(String branch){
this.branch = branch;
return this;
}
public Builder openingBalance(double balance){
this.balance = balance;
return this;
}
public BankAccount build(){
//Here we create the actual bank account object, which is always in a fully initialised state when it's returned.
BankAccount account = new BankAccount(); //Since the builder is in the BankAccount class, we can invoke its private constructor.
account.accountNumber = this.accountNumber;
account.owner = this.owner;
account.branch = this.branch;
account.balance = this.balance;
return account;
}
}
}
正如您所看到的,这些方法是按顺序调用的,方法的输出-withOwner
,atBranch
,openingBalance
,是链中的Builder
实例。对我来说,这被称为方法链,因为每个方法的输出都会在以后使用,这一点非常清楚。但是,我的问题是-上面示例1的方法链接如何(BiFunction及其方法链接)
工作内部您可以查看默认实现:
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t, U u) -> after.apply(apply(t, u));
}
default BiFunction,然后(Function它是简单的函数组合,这意味着如果我们给结果函数命名:
BiFunction<String, String, String> composed = bi.andThen(f);
因此BiFunction。然后返回一个BiFunction
,该函数将应用当前(bi
)函数的逻辑来计算结果,然后将结果传递给另一个函数(f
),应用其逻辑返回最终输出。第和第方法与Builder
模式在以下几个方面不同:
然后
返回一个由其他两个函数组成的新函数,而生成器的每个方法都返回自己,只是为了允许方法调用的链接,从而使代码更加紧凑,但您也可以编写:
BankAccount.Builder builder = new BankAccount.Builder("bank_account");
builder.withOwner("account_owner");
builder.atBranch("branch_name");
builder.openingBalance(balance);
BankAccount account = builder.build();
另外,使用和方法,一切都是不可变的,而构建器本身是可变的(尽管构建的对象本身通常是不可变的).我怀疑的文档,然后读取任何地方的链接。除此之外,我认为将Builder
模式与组合函数进行比较毫无意义。是什么导致了这里的混乱?
composed(x,y) = f(bi(x,y))
BankAccount.Builder builder = new BankAccount.Builder("bank_account");
builder.withOwner("account_owner");
builder.atBranch("branch_name");
builder.openingBalance(balance);
BankAccount account = builder.build();