JAVA

Builder Pattern in Java

seoca 2019. 8. 9. 05:53

 

 

Builder Pattern 

Builder pattern is how you create a complex object especially when you have many arguments.

It gives apparent division between the construction and representation of an object

 

 

Example Code

 

 
public class BuilderPattern {
    private long id;
    private String name;
    private String email;
    private String phone;
    private String address;
 
    //Inner static class
    public static class Builder{
        //Essential parameters
        private final long id;
        private final String name;
        //Optional parameters
        private String email = "";
        private String phone = "";
        private String address = "";
 
        public Builder(long id, String name) {
            this.id = id;
            this.name = name;
        }
 
//Setter methods. return 'this' reference
        public Builder email(String email) {
            this.email = email;
            return this; //객체 자신의 참조값 전달. Chain method 사용가능
        }
 
        public Builder phone(String phone) {
            this.phone = phone;
            return this;
        }
 
        public Builder address(String address) {
            this.address = address;
            return this;
        }
 
        public BuilderPattern build() {
            return new BuilderPattern(this);
        }
    }
 
    private BuilderPattern(Builder builder) {
        this.id = builder.id;
        this.name = builder.name;
        this.email = builder.email;
        this.phone = builder.phone;
        this.address = builder.address;
    }
 
    @Override
    public String toString() {
        return "id:" + id + " name:" + name + " email:" + email + " phone:" + phone + " address:" + address;
    }
}
 
 

 

 

Main

 

 
public class Main {
 
    public static void main(String[] args) {
        BuilderPattern.Builder builder = new BuilderPattern.Builder(1"jen");
        builder.email("jen@gmail.com");
        builder.phone("2182849334");
        builder.address("Vancouver, CA");
        BuilderPattern person = builder.build();
 
        System.out.println(person.toString());
 
        // Method chaining
        BuilderPattern builder2 = new BuilderPattern
                .Builder(2"jin")    // essential input
                .phone("6474481029")
                .address("Toronto, CA")
                .build();  // build() returns Object
 
        System.out.println(builder2.toString());
    }
}
 

 

 

 

Output

 

id:1 name:jen email:jen@gmail.com phone:2182849334 address:Vancouver, CA
id:2 name:jin email: phone:6474481029 address:Toronto, CA

 

 

 

 

Reference

https://johngrib.github.io/wiki/builder-pattern/

https://asfirstalways.tistory.com/350