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 :

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

Popular posts from this blog

Spring | Using TIBCO EMS with Spring framework

TIBCO | For Loop - Accumulate output

TIBCO | JNDI Server & JMS Instance creation