[Design pattern] Builder Pattern

1 minute read

This is the article of design pattern series. I will continuouly write. Second one is builder.

This is the definition of Builder from wikipedia.

The builder pattern is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. The intent of the Builder design pattern is to separate the construction of a complex object from its representation. It is one of the Gang of Four design patterns.

1. Adventage

  • you don’t need to make unecessary Contruct
  • you don’t be confused from making Contruct which has many parameter
  • you are easy to add new variable in class
  • you can manage object to be complete state and immutably

2. Disadventage

  • you need to type more code
  • you need to create seperate ConcreteBuilder for different type for Product.

3. example(java version)

public class main{
    public static void main(String[] args){
        department cs = new department
                .Builder(1,"CS","Engineering")
                .setDean("TimKim")
                .SetNumberOfStudent(100)
                .build();
        
    }
}

class department {
    private int deptCode;
    private String deptName;
    private String upperCollege;
    private int numberofStudent;
    private String dean;

    public static class Builder{
        //require
        private int deptCode;
        private String deptName;
        private String upperCollege;

        // option
        private int numberofStudent;
        private String dean;

        public Builder(int code,String name, String college){
            this.deptCode = code;
            this.deptName = name;
            this.upperCollege = college;
        }

        public Builder setNumberOfStudent(int num){
            this.numberofStudent = num;
            return this;
        }
        public Builder setDean(String deanName){
            this.dean = deanName;
            return this;
        }

        public department build(){
            return new department(this);
        }
    }

    private department(Builder builder){
        deptCode = builder.deptCode;
        deptName = builder.deptName;
        upperCollege = builder.upperCollege;
        numberofStudent = builder.numberofStudent;
        dean = builder.dean;
    }    
    
    @Override
    public String toString() {
        return "department{" +
                "deptCode=" + deptCode +
                ", deptName='" + deptName + '\'' +
                ", upperCollege='" + upperCollege + '\'' +
                ", numberofStudent=" + numberofStudent +
                ", dean='" + dean + '\'' +
                '}';
    }
}

Output:

department{deptCode=1, deptName='CS', upperCollege='Engineering', numberofStudent=100, dean='TimKim'}

Leave a comment