Builder Pattern:is to find a solution to the telescoping constructor.
The telescoping constructor anti-pattern occurs when the increase of object constructor
parameter combination leads to an exponential list of constructors. Instead of using numerous constructors,
the builder pattern uses another object, a builder that receives each initialization parameter step by step
and then returns the resulting constructed object at once.
Example
Account.java
package com.builderpattern.example; public class Account { // Mandatory Field private int accountNo; // Mandatory Field private String accountName; // Optional Field private String lastName; // Optional Field private int faxNo; private Account(AccountBuilder accountBuilder) { this.accountNo = accountBuilder.accountNo; this.accountName = accountBuilder.accountName; this.lastName = accountBuilder.lastName; this.faxNo = accountBuilder.faxNo; } public int getAccountNo() { return accountNo; } public String getFirstName() { return accountName; } public String getLastName() { return lastName; } public int getFaxNo() { return faxNo; } public String toString() { StringBuilder accountDetails = new StringBuilder(); accountDetails.append("Account created Successfully with Acccount No "); accountDetails.append(accountNo); accountDetails.append(" and Account Name "); accountDetails.append(accountName); accountDetails.append(" and Account lastName "); accountDetails.append(lastName); accountDetails.append(" faxNo "); accountDetails.append(faxNo); return accountDetails.toString(); } public static class AccountBuilder { private int accountNo; private String accountName; private String lastName; private int faxNo; // Mandatory Field are set using constructor public AccountBuilder(int accountNo, String accountName) { this.accountNo = accountNo; this.accountName = accountName; } // Optional Field are set using method public AccountBuilder setlastName(String lastName) { this.lastName = lastName; return this; } // Optional Field are set using method public AccountBuilder setfaxNo(int faxNo) { this.faxNo = faxNo; return this; } public Account build() { return new Account(this); } } }
AccountTestDrive.java
package com.builderpattern.example; public class AccountTestDrive { public static void main(String[] args) { //Mandatory fields are set using Constructor and thus avoiding telescoping Constructor Account account = new Account.AccountBuilder(123456,"XYZ").build(); System.out.println(account); //Setting optional Fields Account account2 = new Account.AccountBuilder(123457,"XYC").setfaxNo(854555).build(); System.out.println(account2); } }
Home
No comments:
Post a Comment