vendredi 23 novembre 2018

Is the following an anti pattern?

I have a class which consists of only methods and no state. Since it has methods only, I want to make it a singleton class.

 public class SomeSingleton implements SomeInterface {
    private static SomeSingleton instance;

    private SomeSingleton() {}

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

    // interface methods implementations
 }

Now when I test this class, inside the test I have to use this getInstance() method:

 @Test
 public void someMethodTest() {
   SomeSingleton singleton = SomeSingleton.getInstance();
   //test lines
 }

Is this an anti pattern? I get a gut feeling that this is not the right way. Is there some more elegant way of doing it?

Aucun commentaire:

Enregistrer un commentaire