SHARE
TWEET

Ordered builder example

teabot May 25th, 2011 220 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.Collections;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4.  
  5. public class Person {
  6.  
  7.   private final int id;
  8.   private final String name;
  9.   private final int age;
  10.   private final Set<String> pets;
  11.  
  12.   private Person(Builder builder) {
  13.     this.id = builder.id;
  14.     this.name = builder.name;
  15.     this.age = builder.age;
  16.     this.pets = Collections.unmodifiableSet(builder.pets);
  17.   }
  18.  
  19.   public int getId() {
  20.     return id;
  21.   }
  22.  
  23.   public String getName() {
  24.     return name;
  25.   }
  26.  
  27.   public int getAge() {
  28.     return age;
  29.   }
  30.  
  31.   public Set<String> getPets() {
  32.     return pets;
  33.   }
  34.  
  35.   @Override
  36.   public String toString() {
  37.     return "Person [id=" + id + ", name=" + name + ", age=" + age + ", pets=" + pets + "]";
  38.   }
  39.  
  40.   public static class Builder {
  41.  
  42.     private int id;
  43.     private String name;
  44.     private int age;
  45.     private Set<String> pets;
  46.  
  47.     private final NameMandatoryFieldBuilder mandatoryFieldName;
  48.     private final OptionalFieldsBuilder optionalFields;
  49.  
  50.     public Builder() {
  51.       pets = new HashSet<String>();
  52.       mandatoryFieldName = new NameMandatoryFieldBuilder(this);
  53.       optionalFields = new OptionalFieldsBuilder(this);
  54.     }
  55.  
  56.     public NameMandatoryFieldBuilder id(int id) {
  57.       this.id = id;
  58.       return mandatoryFieldName;
  59.     }
  60.  
  61.   }
  62.  
  63.   public static class NameMandatoryFieldBuilder {
  64.     private final Builder builder;
  65.  
  66.     private NameMandatoryFieldBuilder(Builder builder) {
  67.       this.builder = builder;
  68.     }
  69.  
  70.     public OptionalFieldsBuilder name(String name) {
  71.       builder.name = name;
  72.       return builder.optionalFields;
  73.     }
  74.   }
  75.  
  76.   public static class OptionalFieldsBuilder {
  77.     private final Builder builder;
  78.  
  79.     private OptionalFieldsBuilder(Builder builder) {
  80.       this.builder = builder;
  81.     }
  82.  
  83.     public OptionalFieldsBuilder age(int age) {
  84.       builder.age = age;
  85.       return builder.optionalFields;
  86.     }
  87.  
  88.     public OptionalFieldsBuilder pets(String... pets) {
  89.       for (String pet : pets) {
  90.         builder.pets.add(pet);
  91.       }
  92.       return builder.optionalFields;
  93.     }
  94.  
  95.     public Person build() {
  96.       return new Person(builder);
  97.     }
  98.  
  99.   }
  100.  
  101. }
RAW Paste Data
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top