I am building a builder based on Joshua's builder pattern. my question is how can I make it singleton? to elaborate my point, if I have the below builder
public class Widget {
public static class Builder {
private String name;
public Builder( String name) {
this.name = name;
}
public Widget build() {
Widget result = new Widget(this);
return result;
}
public Builder model( String value ) {
this.model = value;
return this;
}
}
private final String name;
private Widget( Builder b ) {
this.name = b.name;
}
// ... etc. ...
}
I would call this builder from another class like new Widget.Builder().name("abc").build()........
but what if I want only one instance of this Widget or I have a need to access this Widget from multiple places without resorting to creating a new one every time. Ideally I would like to confine the instantiation with in the Widget class. Any thoughts?
IMHO, Singleton and Builder Patterns don't seem to go together: why would you need a builder if there is only one instance to build?
If what you need is to reuse a Builder object because you want to build a similar object several times, you can simply keep a reference to that Builder and use it as many times as you want (since you made it static):
Widget.Builder builder = new Widget.Builder("abc").model("def");
Then you can create several Widgets:
Widget w1 = builder.build();
Widget w2 = builder.build();
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With