Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton and Builder(Joshua's way)

Tags:

java

builder

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?

like image 306
Java Avatar asked Jan 16 '23 22:01

Java


1 Answers

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();
...
like image 151
assylias Avatar answered Jan 25 '23 14:01

assylias