This looks like a form of the builder pattern (though really, it's not).
Usually (using your example and assuming it's immutable) it follows a pattern similar to this:
public class MyObject {
private final String name;
private final int height;
private final int width;
private final String color;
private final int age;
private MyObject(Builder builder) { // Notice this is private
name = builder.name;
height = builder.height;
width = builder.width;
color = builder.color;
age = builder.age;
}
// Getters
public static class Builder {
// Initialize these to defaults if you have any
private String name;
private int height;
private int width;
private String color;
private int age;
// Getters as usual
// Every setter looks like this:
public Builder setName(String name) {
this.name = name;
return this;
}
// Other setters
public MyObject build() {
return new MyObject(this);
}
}
}
Then to use it:
MyObject obj = new MyObject.Builder()
.setName("Foo")
.setHeight(5)
.setWidth(3)
.setColor("blue")
.setAge(7)
.build();
You can also reuse the builder:
MyObject.Builder builder = new MyObject.Builder();
MyObject obj1 = builder
.setName("Foo")
.setHeight(5)
.setWidth(3)
.setColor("blue")
.setAge(7)
.build();
MyObject obj2 = builder
.setName("Bar")
.build();
Here, obj2
will have the same properties as obj1
for all but name
.
This is usually an alternative to long constructors. It can also be used for an object where all the information isn't available immediately and you don't want to declare a bunch of variables yourself everywhere you need to create your object. From the last example, you see it can be used if you have lots of objects you want to initialize with the same properties without having to pass those properties over and over again.
The result is that you have an immutable object, but you don't have to set/pass all of the variables at the same time like you would with a constructor or a static factory method.
Here are some references:
- Wikipedia builder pattern page
- OODesign.com's builder pattern page (also details how you can use interfaces for the builder pattern)
- Joshua Bloch's Effective Java - 2nd Edition is an excellent source of information about some of the patterns (and anti-patterns) in Java.