SE450: Taxonomy: The Builder Pattern [58/63] Previous pageContentsNext page

Mutable data classes are useful for building objects incrementally.

This is called the builder pattern.

A builder is an object that is used to create an object of another class. Usually the builder is used to create exactly one other object, then discarded.

The important part of the following example is toPair, which converts the mutable class to the immutable companion class.

   +------------------------+ <<creates>>  +---------------+
   | PairBuilder            |- - - - - - ->| <<immutable>> |
   +------------------------+              |      Pair     |
   | setFirst(Object):void  |              +---------------+
   | setSecond(Object):void |
   | toPair():Pair          |
   +------------------------+

file:Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package basics.mutablebasic;
import basics.immutabledata.Pair;
public class Main {
  private Main() {}
  static public void main (final String[] args) {
    //stdlib.Trace.graphvizShowSteps (true); stdlib.Trace.run ();
    final PairBuilder<Integer,String> pb1 = new PairBuilder<Integer,String>();
    pb1.setFirst(42);
    pb1.setSecond("dog");
    System.out.println(pb1);
    final Pair<Integer,String> p1 = pb1.toPair();
    System.out.println(p1);

    final PairBuilder<Integer,String> pb2 = new PairBuilder<Integer,String>();
    final Pair<Integer,String> p2 = pb2.toPair();
  }
}
final class PairBuilder<S extends Comparable<S>, T extends Comparable<T>> {
  private S x;
  private T y;
  public PairBuilder() { }
  public void setFirst(S x) { this.x = x; }
  public void setSecond(T y) { this.y = y; }
  public Pair<S,T> toPair() {
    if (x == null || y == null)
      throw new NullPointerException();
    return new Pair<S,T>(x,y);
  }
}

Previous pageContentsNext page