Java | Builder Design Pattern
Java POJO classes can be created using different design patterns. Below is example how Builder pattern works.
Normally, Simple java POJO class setter-call has void return type. Builder pattern replace void return type and returns current object of class(ie. return this). Builder pattern can be used to replace parameterised constructor. Also when we create object the code is more readable.
Example :
Normally, Simple java POJO class setter-call has void return type. Builder pattern replace void return type and returns current object of class(ie. return this). Builder pattern can be used to replace parameterised constructor. Also when we create object the code is more readable.
Example :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.rohan; | |
public class Customer { | |
private String fname; | |
private String lname; | |
private int age; | |
@Override | |
public String toString() { | |
return "Customer{" + | |
"fname='" + fname + '\'' + | |
", lname='" + lname + '\'' + | |
", age=" + age + | |
", address='" + address + '\'' + | |
'}'; | |
} | |
private String address; | |
public String getFname() { | |
return fname; | |
} | |
public Customer setFname(String fname) { | |
this.fname = fname; | |
return this; | |
} | |
public String getLname() { | |
return lname; | |
} | |
public Customer setLname(String lname) { | |
this.lname = lname; | |
return this; | |
} | |
public int getAge() { | |
return age; | |
} | |
public Customer setAge(int age) { | |
this.age = age; | |
return this; | |
} | |
public String getAddress() { | |
return address; | |
} | |
public Customer setAddress(String address) { | |
this.address = address; | |
return this; | |
} | |
} | |
//Customer test class | |
package com.rohan; | |
public class CustomerTest { | |
public static void main(String[] args) { | |
Customer customer = new Customer(); | |
customer.setFname("Rohan") | |
.setLname("Lopes") | |
.setAge(25) | |
.setAddress("Mumbai, India"); | |
System.out.println(customer); | |
} | |
} |
Comments
Post a Comment