dimanche 17 novembre 2019

Singleton using getInstance vs public declaration

What's the point in creating getInstance() when you can just make the variable public and access the instance?

I am aware of the abstract factory design pattern which makes sense with factories since we decide on run-time the kind of implementation we need.

Using getInstance():

public class ClientFactory {
    private static final ClientFactory instance = null;

    private ClientFactory() { }

    public static synchronized ClientFactory getInstance() {
        if ( instance == null ) {
            instance = new ClientFactory();
        }
        return instance;
    }
}

Making variable public instead of creating instance method:

 public class ClientFactory {
    public static ClientFactory instance = new ClientFactory ();
    private ClientFactory() { }
 }

and we can easily get the accesses using ClientFactory.instance.foo();.

Aucun commentaire:

Enregistrer un commentaire