1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
public class Car { public static class Builder { private int year; private String make; private String model; private String color; public Builder year(int year) { this.year = year; return this; } public Builder make(String make) { this.make = make; return this; } public Builder model(String model) { this.model = model; return this; } public Builder color(String color) { this.color = color; return this; } public Car build() { return new Car(year, make, model, color); } } private final int year; private final String make; private final String model; private final String color; private Car(int year, String make, String model, String color) { this.year = year; this.make = make; this.model = model; this.color = color; } public static Builder builder() { return new Builder(); } } // Using this fluent API... Car car = Car.builder() .year(2007) .make("Toyota") .model("Camry") .color("blue") .build();
Refactorings
No refactoring yet !
askalon
January 23, 2008, January 23, 2008 21:02, permalink
A little bit shorter version.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
public class Car { public static class Builder { private final Car car = new Car(); public Builder year(int year) { car.year = year; return this; } public Builder make(String make) { car.make = make; return this; } public Builder model(String model) { car.model = model; return this; } public Builder color(String color) { car.color = color; return this; } public Car build() { return car; } } private int year; private String make; private String model; private String color; private Car() { } public static Builder builder() { return new Builder(); } }
Here's an example of the Builder pattern using a fluent interface, what I like to call a fluent builder (discussed at http://jeronrails.blogspot.com/2007/12/fluent-builders.html). There's some duplication and I think there's potential for refactoring. Give it a go!