Without using the Builder pattern what you can do is
public class MyImmutableClass {
final private String foo;
final private String bar;
public MyImmutableClass(String f, String b) {
this.foo = f;
this.bar = b;
}
// only getters
}
The way it work is
- make all fields final
- provide no setters
- make sure subclass can't override any method ( make the class final )
The builder pattern comes handy in case the number of params in the constructor increases. You are just using the builder to make your code more maintainable and readable but the strategy is almost same i.e it also permit object manipulation only through the inner static class and expose read only (getters) methods in the main/outer class
Another reason for using builder could be in a situation where your object has some mandatory as well as optional parameters.
public class Item {
// private fields & getters
public static class Builder {
// same private fields
public Builder(String f, String b) {
// set values
}
...
...
}
}
Here you can use the inner public Builder(String f, String b)
constructor to take two mandatory parameters keeping the rest as optional
If the number of parameters is less I think the first strategy work much better than implementing builder, as it has the drawbacks of code duplication (builder needs to copy all fields from the outer class)