This is a variant of the Builder template described by Lawrence above.
I use this a lot (in suitable places).
The main difference is that in this case the Builder is immuatable. This has the advantage of being reusable and thread safe.
So, you can use this to create one default Builder, and then in different places where you need it, you can customize it and build your object.
It makes sense if you build the same object over and over again, because then you can make a static builder and not worry about changing it.
On the other hand, if you need to create objects with variable parameters, this calms some costs a bit. (but hey, you can combine static / dynamic generation with custom build methods)
Here is a sample code:
public class Car { public enum Color { white, red, green, blue, black }; private final String brand; private final String name; private final Color color; private final int speed; private Car( CarBuilder builder ){ this.brand = builder.brand; this.color = builder.color; this.speed = builder.speed; this.name = builder.name; } public static CarBuilder with() { return DEFAULT; } private static final CarBuilder DEFAULT = new CarBuilder( null, null, Color.white, 130 ); public static class CarBuilder { final String brand; final String name; final Color color; final int speed; private CarBuilder( String brand, String name, Color color, int speed ) { this.brand = brand; this.name = name; this.color = color; this.speed = speed; } public CarBuilder brand( String newBrand ) { return new CarBuilder( newBrand, name, color, speed ); } public CarBuilder name( String newName ) { return new CarBuilder( brand, newName, color, speed ); } public CarBuilder color( Color newColor ) { return new CarBuilder( brand, name, newColor, speed ); } public CarBuilder speed( int newSpeed ) { return new CarBuilder( brand, name, color, newSpeed ); } public Car build() { return new Car( this ); } } public static void main( String [] args ) { Car porsche = Car.with() .brand( "Porsche" ) .name( "Carrera" ) .color( Color.red ) .speed( 270 ) .build() ;
Scheintod Sep 16 '15 at 18:33 2015-09-16 18:33
source share