How to Implement the Builder Pattern in Java


In this example we will show how to implement java builder design pattern.

Source Code

(1)Person.java

package com.beginner.examples;

public class Person {
    private String name;
    private int age;
    private boolean sex;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public boolean isSex() {
        return sex;
    }

    public static class Builder {
        private String name;
        private int age;
        private boolean sex;

        public Builder name(String n) {
            name = n;
            return this;
        }

        public Builder age(int a) {
            age = a;
            return this;
        }

        public Builder sex(boolean s) {
            sex = s;
            return this;
        }

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

    private Person(Builder builder) {
        name = builder.name;
        age = builder.age;
        sex = builder.sex;
    }
}

(2)TestMain.java

package com.beginner.examples;

public class TestMain {

	public static void main(String[] args) {

		Person person = new Person.Builder().name("Alice").age(20).sex(true).build();
		System.out.println(person.getName() + "n" + person.getAge() + "n" + person.isSex());

	}

}

Output:

Alice
20
true
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments