jeudi 24 octobre 2019

Singleton Pattern: getInstance() vs Passing the singleton object?

What is the right / most popular way to utilize the Singleton Pattern.

  1. Limit the no. of calls to getInstance(), preferably call it only once, and pass the object around to other classes during their instantiation?
class SingletonClass {
// Implementataion
}

class MainClass {
    private SingletonClass singletonClassObject;

    public MainClass() {
        singletonClassObject = SingletonClass.getInstance();
        new SomeClass(singletonClassObject).doSomething();
        new SomeOtherClass(singletonClassObject).doSomethingElse();
    }
}

class SomeClass {
    private SingletonClass singletonClassObject;

    public SomeClass(SingletonClass singletonClassObject) {
        this.singletonClassObject = singletonClassObject;
    }

    public void doSomething() {
        System.out.println(singletonClassObject.getStuff());
    }
}

class SomeOtherClass {
    private SingletonClass singletonClassObject;

    public SomeOtherClass(SingletonClass singletonClassObject) {
        this.singletonClassObject = singletonClassObject;
    }

    public void doSomethingElse() {
        System.out.println(singletonClassObject.getStuff());
    }
}

  1. Don't pass the singleton object around. Rather call get the object reference in each class and save the reference as an instance variable and use it wherever required.
class SingletonClass {
// Implementataion
}

class MainClass {
    public MainClass() {
        new SomeClass().doSomething();
        new SomeOtherClass().doSomethingElse();
    }
}

class SomeClass {
    private SingletonClass singletonClassObject;

    public SomeClass() {
        singletonClassObject = SingletonClass.getInstance();
    }

    public void doSomething() {
        System.out.println(singletonClassObject.getStuff());
    }
}

class SomeOtherClass {
    private SingletonClass singletonClassObject;

    public SomeOtherClass() {
        singletonClassObject = SingletonClass.getInstance();
    }

    public void doSomethingElse() {
        System.out.println(singletonClassObject.getStuff());
    }
}

  1. Don't even save the reference as an instance variable, rather use SingletonClass.getInstance() everywhere you need the object.
class SingletonClass {
// Implementataion
}

class MainClass {
    public MainClass() {
        new SomeClass().doSomething();
        new SomeOtherClass().doSomethingElse();
    }
}

class SomeClass {
    public SomeClass() {
    }

    public void doSomething() {
        System.out.println(SingletonClass.getInstance().getStuff());
    }
}

class SomeOtherClass {
    public SomeOtherClass() {
    }

    public void doSomethingElse() {
        System.out.println(SingletonClass.getInstance().getStuff());
    }
}

How do these approaches compare with each other w.r.t. better design, testability etc? Which is better and why?

Aucun commentaire:

Enregistrer un commentaire