1
我在我的應用程序中有兩個單例,這裏是我的問題: 他們每個人都需要對方,所以我不能建立任何兩個,因爲我會得到一個stackOverflowError。如何克服它?如何創建一對一的單身關係
public class ApplicationService {
private ApplicationDao applicationDao;
private DerogationService derogationService;
private LogService logService;
private static ApplicationService applicationServiceInstance;
private ApplicationService()
{
applicationDao = ApplicationDao.getInstance();
derogationService = DerogationService.getInstance();
logService = LogService.getInstance();
}
public static synchronized ApplicationService getInstance(){
if(applicationServiceInstance == null)
{
applicationServiceInstance = new ApplicationService();
}
return applicationServiceInstance;
}
。
public class DerogationService {
private DerogationDao derogationDao;
private ApplicationService applicationService;
private DroitService droitService;
private static DerogationService derogationServiceInstance;
private DerogationService(){
applicationService = ApplicationService.getInstance();
droitService = DroitService.getInstance();
derogationDao = DerogationDao.getInstance();
}
public static synchronized DerogationService getInstance(){
if(derogationServiceInstance == null)
{
derogationServiceInstance = new DerogationService();
}
return derogationServiceInstance;
}
Thx guys! :)
如何只調用' .getInstance()'當你需要其他類的實例,而不是將其存儲在字段中? –
因爲我經常調用該方法,所以我認爲這種方式的代碼可讀性較差。 我很肯定它必須是這樣做的一種方式 – Antoine
如果對其他singletone的引用是'null',則可以在每個構造函數中添加一個'null'檢查以僅調用'getInstance()'。 – Titus