Monday 30 July 2018

Builder Pattern

We can build the object as per our convenience, 
there is no hard rule to pass certain amount of parameters.

For example, if we have a constructor with 3 parameters, 
and if we need to create an object, 
we need to pass the values to the constructors even if we don't know what is age. 

To avoid it, we can use Builder pattern. 
Where we can build the object based on the values we have.

public class Employee {
    private String empname;
    private String age;
    private String department;

    public String getEmpname() {
        return empname;
    }

    public Employee setEmpname(String empname) {
        this.empname = empname;
        return this;
    }

    public String getAge() {
        return age;
    }

    public Employee setAge(String age) {
        this.age = age;
        return this;
    }

    public String getDepartment() {
        return department;
    }

    public Employee setDepartment(String department) {
        this.department = department;
        return this;
    }
}

public class EmployeeTest {
    public static void main(String[] args) {
        Employee emp = new Employee();
        emp.setAge("10").setDepartment("IT").setEmpname("Doll");

        System.out.println(emp.getDepartment());
    }
}

No comments:

Post a Comment