Explain a use case for the Builder Design Pattern

Technology CommunityCategory: JavaExplain a use case for the Builder Design Pattern
VietMX Staff asked 3 years ago

The good example is a class hierarchy that adds more parameters as it goes down the chain. At the bottom, some of the classes can have up to N parameters, N-2 of which are just being passed into the super constructor. Instead of using a particular constructor with N params we could use theĀ Builder Design Pattern.

Consider the following example:

public class StudentBuilder
{
    private String _name;
    private int _age = 14;      // this has a default
    private String _motto = ""; // most students don't have one

    public StudentBuilder() { }

    public Student buildStudent()
    {
        return new Student(_name, _age, _motto);
    }

    public StudentBuilder name(String _name)
    {
        this._name = _name;
        return this;
    }

    public StudentBuilder age(int _age)
    {
        this._age = _age;
        return this;
    }

    public StudentBuilder motto(String _motto)
    {
        this._motto = _motto;
        return this;
    }
}

This lets us write code like:

Student s1 = new StudentBuilder().name("Eli").buildStudent();
Student s2 = new StudentBuilder()
                 .name("Spicoli")
                 .age(16)
                 .motto("Aloha, Mr Hand")
                 .buildStudent();