1public class BankAccount {
2 public static class Builder {
3 private long accountNumber; //This is important, so we'll pass it to the constructor.
4 private String owner;
5 private String branch;
6 private double balance;
7 private double interestRate;
8 public Builder(long accountNumber) {
9 this.accountNumber = accountNumber;
10 }
11 public Builder withOwner(String owner){
12 this.owner = owner;
13 return this; //By returning the builder each time, we can create a fluent interface.
14 }
15 public Builder atBranch(String branch){
16 this.branch = branch;
17 return this;
18 }
19 public Builder openingBalance(double balance){
20 this.balance = balance;
21 return this;
22 }
23 public Builder atRate(double interestRate){
24 this.interestRate = interestRate;
25 return this;
26 }
27 public BankAccount build(){
28 //Here we create the actual bank account object, which is always in a fully initialised state when it's returned.
29 BankAccount account = new BankAccount(); //Since the builder is in the BankAccount class, we can invoke its private constructor.
30 account.accountNumber = this.accountNumber;
31 account.owner = this.owner;
32 account.branch = this.branch;
33 account.balance = this.balance;
34 account.interestRate = this.interestRate;
35 return account;
36 }
37 }
38 //Fields omitted for brevity.
39 private BankAccount() {
40 //Constructor is now private.
41 }
42 //Getters and setters omitted for brevity.
43}
44
45BankAccount account = new BankAccount.Builder(1234L)
46 .withOwner("Marge")
47 .atBranch("Springfield")
48 .openingBalance(100)
49 .atRate(2.5)
50 .build();
51BankAccount anotherAccount = new BankAccount.Builder(4567L)
52 .withOwner("Homer")
53 .atBranch("Springfield")
54 .openingBalance(100)
55 .atRate(2.5)
56 .build();