我有一個單例類,必須作爲服務公開給其他使用接口的應用程序。通過接口暴露單例類的正確方法
例如:
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