RSS Feed for This PostCurrent Article

Java: Create Immutable Object using Builder Pattern

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


Trackback URL


1 Trackback(s)

  1. From Along Came Betty » Porting Soar to Java or: How I Learned to Stop Worrying and Love Spaghetti (Part 2) | Dec 26, 2008

Sorry, comments for this entry are closed at this time.