Commenting omitted to give you the idea. I've been toying with this recently as a variant of the Builder pattern. I've recently fallen in love with immutable objects for the benefits they give in larger concurrent systems.
Questions:
Is there a way to do this without having to instantiate two Objects? (ie. Something.Mutable extends Something
but adds setters, while preserving final
on the underlying fields once the object gets finalized?
If I have to instantiate two Objects, can I keep final
on their somehow and not repeat myself in the contained Builder Object?
public class Something {
private final int someInteger;
private final String someString;
public Something(int someInteger, String someString) {
this.someInteger = someInteger;
this.someString = someString;
}
public int getSomeInteger() { return someInteger; }
public String getSomeString() { return someString; }
public static class Mutable {
private int someInteger;
private String someString;
public Something.Mutable() {}
public int getSomeInteger() { return someInteger; }
public String getSomeString() { return someString; }
public Something.Mutable setSomeInteger(int someInteger) {
this.someInteger = someInteger;
return this;
}
public Something.Mutable setSomeString(String someString) {
this.someString = someString;
return this;
}
public Something build() {
return new Something(someInteger, someString);
}
}
}
Here is an example of me using it:
Something something = new Something.Mutable()
.setString("hi")
.setInteger(42)
.build();
Mutable
, and you need to rename thefinalize
method (which is already defined inObject
). – Landei May 6 '12 at 20:56