lundi 5 octobre 2015

proper way of exposing singleton class through interface

I have a singleton class that has to be exposed as a service to other applications using interface.

for example:

public class MySingleSingletonClass{

    private static final MySingleSingletonClass THIS_INSTANCE = new MySingleSingletonClass();

    private MySingleSingletonClass() {}

    public static MySingleSingletonClass getInstance(){
       return THIS_INSTANCE;
    }

    //do other staff
   public int methodA(){
     //some service
   }

}

Now if I want to expose all the services of this class through interface, here is my first attempt :

public interface MyServiceInterface{
    int methodA();
    MyServiceInterface getInstanceThroughService(); 
}

and when MySingleSingletonClass implements this interface :

public class MySingleSingletonClass implements MyServiceInterface{

    private static final MySingleSingletonClass THIS_INSTANCE = new MySingleSingletonClass();

    private MySingleSingletonClass() {}

    public static MySingleSingletonClass getInstance(){
       return THIS_INSTANCE;
    }

   @Override
   public int methodA(){
     //some service
   }

   @Override
   MyServiceInterface getInstanceThroughService(){
     return MySingleSingletonClass.getInstance();
   }

}

I see two problems with this kind of implementation,

first if I use a framework like spring, and I try to get a bean of type MyServiceInterface how will the class be instantiated? I read that spring will still call the private contractor of the class using reflection. will this instance still be singleton ?

Second, if Spring gives me the instance already, I don't see the point of calling getInstanceThroughService() method using the instance itself. feels like there is a problem with this implementation.

thank you

Aucun commentaire:

Enregistrer un commentaire