Example of Builder Pattern in Java API?

17,036

Solution 1

I'm not sure about within the core JDK, but good examples can be found in Guava. MapMaker is probably the best example I can think of off the top of my head. For example, from the docs:

ConcurrentMap<Key, Graph> graphs = new MapMaker()
    .concurrencyLevel(32)
    .softKeys()
    .weakValues()
    .expiration(30, TimeUnit.MINUTES)
    .makeComputingMap(
        new Function<Key, Graph>() {
          public Graph apply(Key key) {
            return createExpensiveGraph(key);
          }
        });

Yes, this sort of thing can go against the grain of "standard" Java naming, but it can also be very readable.

For situations where you're not returning "this" but a new object (typically with immutable types) I like a "with" prefix - Joda Time uses that pattern extensively. That's not the builder pattern, but an alternative and related construction form.

Solution 2

Locale class has an example of the Builder pattern. https://docs.oracle.com/javase/7/docs/api/java/util/Locale.Builder.html

Usage:

Locale locale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build();

Solution 3

The only builder most accurate to the Effective java book is StringBuilder. The only difference I see from the example is that this builder is not an inner class of String.

All the methods return the builder object to chain. and the toString() method is the build() method.

Solution 4

Pretty good example from Java 8 Core API is Calendar, for example you can use:

Calendar cal = new Calendar.Builder().setCalendarType("iso8601")
                        .setWeekDate(2013, 1, MONDAY).build();

Another good example from Java 7 is Locale, use:

Locale aLocale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build();

The builder pattern is most useful in the context of immutable objects. Interestingly there are many mutable builders in Java, StringBuilder being the most common one. Mutable builders from Java 8:

  • Stream.Builder
  • IntStream.Builder
  • LongStream.Builder
  • DoubleStream.Builder

Solution 5

SAXParser seems to be a good example:

  • SAXParser - Director
  • ContentHandler - Builder

The typical usage of SAXParser is identical with Builder:

// Create Director
SAXParser parser = new org.apache.xerces.parsers.SAXParser();  
// Create Concrete Builder (our own class)
IndentingContentHandler handler = new IndentingContentHandler();
// Set Builder to Director
parser.setContentHandler(handler);
// Build
parser.parse(new InputSource(new FileReader(fileName));
// Get indented XML as String from handler
String indentedXML = handler.getResult();
Share:
17,036
Fostah
Author by

Fostah

Updated on June 15, 2022

Comments

  • Fostah
    Fostah about 2 years

    Joshua Bloch's Effective Java describes a Builder Pattern that can be used to build objects with several optionally customizable parameters. The naming convention he suggests for the Builder functions, which "simulates named optional parameters as found in Ada and Python," doesn't seem to fall in line with Java's standard naming convention. Java functions tend to rely on a having a verb to start the function and then a noun-based phrase to describe what it does. The Builder class only has the name of the variable that's to be defined by that function.

    Are there any APIs within the Java standard libraries that makes use of the Builder Pattern? I want to compare the suggestions in the book to an actual implementation within the core set of Java libraries before pursuing its use.