我有一个单例类,必须作为服务公开给其他使用接口的应用程序。通过接口暴露单例类的正确方法
例如:
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
}
}
现在,如果我要揭露这个类通过接口的所有服务,这是我第一次尝试:
public interface MyServiceInterface{
int methodA();
MyServiceInterface getInstanceThroughService();
}
当MySingleSingletonClass实现了这个接口:
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();
}
}
我看到这种实现有两个问题,
第一个如果我使用像Spring这样的框架,并且我尝试获取类型为MyServiceInterface的bean,那么该类将如何实例化?我读过那个春天仍然会用反思来呼叫这个班级的私人承包商。这个例子还会是单身吗?
第二个,如果Spring已经给我这个实例了,我没有看到使用实例本身调用getInstanceThroughService()方法的要点。感觉这个实现有问题。
谢谢
想象不能访问ConsumerA/ConsumerB中的MySingleSingletonClass,只能通过MyServiceInterface访问服务。在这种情况下如何处理? - 谢谢 – LeTex
@LeTex:那么'MySingleSingletonClass'必须实现'MyServiceInterface',两个消费者都会使用'@Autowired private MyServiceInterfaces mssc;'来代替。 – Ralph