Java 遵循生成器模式的确切代码,但出现错误
在阅读了一篇流行的博客文章后,我尝试构建自己的构建器模式,但出现了一个错误,所以我认为我做错了什么。我反复检查了我的代码,但还是不断地出错。所以我决定从博客上复制整个代码,但我仍然得到一个错误,我不知道为什么 blogpost中的代码:Java 遵循生成器模式的确切代码,但出现错误,java,Java,在阅读了一篇流行的博客文章后,我尝试构建自己的构建器模式,但出现了一个错误,所以我认为我做错了什么。我反复检查了我的代码,但还是不断地出错。所以我决定从博客上复制整个代码,但我仍然得到一个错误,我不知道为什么 blogpost中的代码: 您没有在BankAccount类上定义字段,只在Builder上定义字段。在他们实现构建器的文章中有一条评论说“为简洁起见省略字段”。您需要遵循第一个示例,其中: 公共类银行账户{ 私人长帐号; 私人字符串所有者; 私人字符串分支; 私人双平衡; 私人双重利益
您没有在
BankAccount
类上定义字段,只在Builder
上定义字段。在他们实现构建器的文章中有一条评论说“为简洁起见省略字段”。您需要遵循第一个示例,其中:
公共类银行账户{
私人长帐号;
私人字符串所有者;
私人字符串分支;
私人双平衡;
私人双重利益;
公共银行账户(长账号、字符串所有者、字符串分支、双余额、双利率){
this.accountNumber=accountNumber;
this.owner=所有者;
this.branch=分支;
这个平衡=平衡;
this.interestRate=interestRate;
}
//为简洁起见,省略了getter和setter。
}
然后您需要创建getter和setter,并从生成器
调用setter,例如:
公共类银行账户{
//...
公共无效setAccountNumber(长值){
this.accountNumber=值;
}
//在建筑商中
account.setAccountNumber(此.accountNumber);
}
“为简洁起见省略字段”,但错误在于这些字段显然不存在!如果您在代码中省略了它们,那么我们应该怎么做?不要发布代码或错误的图像。您可能需要查看以创建一个。
public class BankAccount {
public static class Builder {
private long accountNumber; //This is important, so we'll pass it to the constructor.
private String owner;
private String branch;
private double balance;
private double interestRate;
public Builder(long accountNumber) {
this.accountNumber = accountNumber;
}
public Builder withOwner(String owner){
this.owner = owner;
return this; //By returning the builder each time, we can create a fluent interface.
}
public Builder atBranch(String branch){
this.branch = branch;
return this;
}
public Builder openingBalance(double balance){
this.balance = balance;
return this;
}
public Builder atRate(double interestRate){
this.interestRate = interestRate;
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;
account.interestRate = this.interestRate;
return account;
}
}
//Fields omitted for brevity.
private BankAccount() {
//Constructor is now private.
}
//Getters and setters omitted for brevity.
}