Java: Create Immutable Object using Builder Pattern
By admin on Aug 31, 2008 in Creational, design pattern, Java, Programming
To create immutable Java object, we should use the Builder Pattern, as described in Effective Java. This is the pattern I normally used now for immutable class.
1: public class Person {
2: private final String name;
3: private final int age;
4: private final String email;
5: private final String mobileNo;
6:
7:
8: public String getName() {
9: return name;
10: }
11:
12: public int getAge() {
13: return age;
14: }
15:
16: public String getEmail() {
17: return email;
18: }
19:
20: public String getMobileNo() {
21: return mobileNo;
22: }
23:
24: public static class Builder {
25: // Mandatory
26: private final String name;
27: private final int age;
28:
29: // Optional
30: private String email;
31: private String mobileNo;
32:
33:
34: public Builder(String name, int age) {
35: this.name = name;
36: this.age = age;
37: }
38:
39: public Builder email(String email) {
40: this.email = email;
41: return this;
42: }
43:
44: public Builder mobileNo(String mobileNo) {
45: this.mobileNo = mobileNo;
46: return this;
47: }
48:
49: public Person build(){
50: return new Person(this);
51: }
52: }
53:
54: private Person(Builder builder){
55: name = builder.name;
56: age = builder.age;
57: email = builder.email;
58: mobileNo = builder.mobileNo;
59: }
60:
61:
62: public static void main(String[] args){
63: Person person = new Person.Builder("jason",28).email("[email protected]").mobileNo("1234567890").build();
64:
65: System.out.println(person.getName());
66: System.out.println(person.getAge());
67: System.out.println(person.getEmail());
68: System.out.println(person.getMobileNo());
69: }
70: }
- Person class constructor is declared as private
- Person class properties cannot be set directly.
- A Builder is used to create the Person instance
- Mandatory properties are part of the Builder constructor arguments
- Fluent interface is used in the Builder class
Ben Hardy | Aug 26, 2010 | Reply
Very nice. That is some tight code right there. I particularly liked the forcing of the builder via private constructor.
It inspired me to take this to its logical extension is to force/guide the user to set every property using a chain which allows only one way to do it. Using a builder that is itself immutable. Hot!
The build method looks ugly of course but this is merely a side effect of java’s syntactic cruft required to make closures work. If you see through that, there is a certain elegance to this: every single variable in this example is final.
Java Version: http://pastebin.com/ipVL8ipX
Scala Version: http://pastebin.com/TASbJC5y
Translated it to Scala to see what it would look like. I think it would be easy to write a tool which generated this builder code at compile time (in either language).
Javin Paul | Oct 23, 2010 | Reply
Here is an example of immutable class and reasons Why String is immutable in Java