2016-05-23 53 views
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! :)

+0

如何只調用' .getInstance()'當你需要其他類的實例,而不是將其存儲在字段中? –

+0

因爲我經常調用該方法,所以我認爲這種方式的代碼可讀性較差。 我很肯定它必須是這樣做的一種方式 – Antoine

+0

如果對其他singletone的引用是'null',則可以在每個構造函數中添加一個'null'檢查以僅調用'getInstance()'。 – Titus

回答

0

我發現如何做到這一點。

public class ApplicationService { 

    private ApplicationDao applicationDao; 
    private DerogationService derogationService; 
    private LogService logService; 
    private static ApplicationService applicationServiceInstance; 

    private ApplicationService() 
    { 
     applicationDao = ApplicationDao.getInstance(); 
     //I don't do it there 
     //derogationService = DerogationService.getInstance(); 
     logService = LogService.getInstance(); 
    } 

    public static synchronized ApplicationService getInstance(){ 
     if(applicationServiceInstance == null) 
     { 
      applicationServiceInstance = new ApplicationService(); 
      // But here, so i won't get this loop problem. 
      applicationServiceInstance.derogationService = DerogationService.getInstance(); 
     } 
     return applicationServiceInstance; 
    } 

THX的傢伙是誰給了我一個想法開始,即使他只是後刪除他的帖子.. 和THX所有的答案

0

正如你在你的OP沒有實際說出它說你有一個循環參考問題。

你可以考慮使用Spring容器(以及其他)來解決這個問題。