Design patterns

patterns4BuilderPattern

Path
pkg8patterns/patterns4BuilderPattern.java
Package
pkg8patterns
Study order
4
Run
Single-file source launch
Command
java pkg8patterns/patterns4BuilderPattern.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg8patterns/patterns4BuilderPattern.java
1package pkg8patterns;2 3/*4 * Builder (Creational)5 * --------------------6 * INTENT: construct a complex object step by step; the same process can create7 *         different representations. Great for many optional parameters.8 * UML: Product , Builder + setX(): Builder + build(): Product (fluent).9 * PROS: readable construction; immutable result; avoids telescoping constructors.10 * CONS: more code than a plain constructor.11 * REAL-WORLD: StringBuilder, Stream.Builder, HttpRequest.newBuilder().12 */13public class patterns4BuilderPattern {14 15    static class Pizza {16        private final String size;17        private final boolean cheese, pepperoni, mushrooms;18 19        private Pizza(Builder b) {20            this.size = b.size;21            this.cheese = b.cheese;22            this.pepperoni = b.pepperoni;23            this.mushrooms = b.mushrooms;24        }25        @Override public String toString() {26            return size + " pizza [cheese=" + cheese + ", pepperoni=" + pepperoni + ", mushrooms=" + mushrooms + "]";27        }28 29        static class Builder {30            private final String size;            // required31            private boolean cheese, pepperoni, mushrooms;   // optional32            Builder(String size) { this.size = size; }33            Builder cheese()    { this.cheese = true; return this; }34            Builder pepperoni() { this.pepperoni = true; return this; }35            Builder mushrooms() { this.mushrooms = true; return this; }36            Pizza build() { return new Pizza(this); }37        }38    }39 40    public static void main(String[] args) {41        Pizza p1 = new Pizza.Builder("Large").cheese().pepperoni().build();42        Pizza p2 = new Pizza.Builder("Medium").cheese().mushrooms().build();43        System.out.println(p1);44        System.out.println(p2);45    }46}