- Spring 5 Design Patterns
- Dinesh Rajput
- 319字
- 2021-07-08 09:59:34
Sample implementation of the Builder design pattern
In the following code example, I am going to create an Account class that has AccountBuilder as an inner class. The AccountBuilder class has a method to create an instance of this class:
package com.packt.patterninspring.chapter2.builder.pattern; public class Account { private String accountName; private Long accountNumber; private String accountHolder; private double balance; private String type; private double interest; private Account(AccountBuilder accountBuilder) { super(); this.accountName = accountBuilder.accountName; this.accountNumber = accountBuilder.accountNumber; this.accountHolder = accountBuilder.accountHolder; this.balance = accountBuilder.balance; this.type = accountBuilder.type; this.interest = accountBuilder.interest; } //setters and getters public static class AccountBuilder { private final String accountName; private final Long accountNumber; private final String accountHolder; private double balance; private String type; private double interest; public AccountBuilder(String accountName,
String accountHolder, Long accountNumber) { this.accountName = accountName; this.accountHolder = accountHolder; this.accountNumber = accountNumber; } public AccountBuilder balance(double balance) { this.balance = balance; return this; } public AccountBuilder type(String type) { this.type = type; return this; } public AccountBuilder interest(double interest) { this.interest = interest; return this; } public Account build() { Account user = new Account(this); return user; } } public String toString() { return "Account [accountName=" + accountName + ",
accountNumber=" + accountNumber + ", accountHolder=" + accountHolder + ", balance=" + balance + ", type="
+ type + ", interest=" + interest + "]"; } }
AccountBuilderTest.java is a demo class that we will use to test the design pattern. Let's look at how to build an Account object by passing the initial information to the object:
package com.packt.patterninspring.chapter2.builder.pattern; public class AccountBuilderTest { public static void main(String[] args) { Account account = new Account.AccountBuilder("Saving
Account", "Dinesh Rajput", 1111l) .balance(38458.32) .interest(4.5) .type("SAVING") .build(); System.out.println(account); } }
You can test this file and see the output on the console:

Now, we've seen the Builder design pattern. In the upcoming Chapter 3, Consideration of Structural and Behavioural Patterns, I will explore another part of the GOF Design Patterns family.
推薦閱讀
- Developing Mobile Web ArcGIS Applications
- Oracle Database In-Memory(架構與實踐)
- INSTANT CakePHP Starter
- Python機器學習經典實例
- C++ 從入門到項目實踐(超值版)
- C語言程序設計
- 微信小程序入門指南
- 零基礎學Python網絡爬蟲案例實戰全流程詳解(入門與提高篇)
- PySide 6/PyQt 6快速開發與實戰
- Learning PHP 7
- Vue.js光速入門及企業項目開發實戰
- 會當凌絕頂:Java開發修行實錄
- Learning Alfresco Web Scripts
- Java EE基礎實用教程
- Lync Server Cookbook