I saw somewhere on SO today a design pattern that was used to illustrate a point about immutable objects in Java. The idea is to allow the user to set the value for whatever properties he wants during construction, and it looks something like this:
MyObject obj = new MyObject().name("Foo")
.height(5)
.width(3)
.color("blue")
.age(7);
Is there a name for this pattern?
In C++ I know you can just return a pointer to this in each function. How is it done the same way in Java?
For immutable objects, do you have to make a new copy of the object for each property you want to set?
If you want to construct an immutable object with approximately this style, you likely want the Builder pattern.
The chaining visible in this is also known as a Fluent interface and is indeed enabled by returning
this.With your code using the fluent interface on the actual object under construction, the object won’t be immutable if all the methods setting things are in fact mutators. If these methods all return a new object instead of
thisit could be immutable.