2016-05-23 18 views
1

私のアプリケーションに2つのシングルトンがあります。ここに問題があります: それぞれが互いに必要なので、2つのうちのどれも構築できませんa stackOverflowErrorそれを乗り越えるには?1対1シングルトンの関係を作成する方法

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みんな! :)

+0

方法について そして、THXのためのThxをフィールドに格納する代わりに、他のクラスのインスタンスが必要ですか? –

+0

私はメソッドを非常に頻繁に呼び出すので、コードはこのように読みにくくなると思います。 私はそれがそのようにする方法でなければならないと確信しています – Antoine

+0

他のsingletoneへの参照が 'null'なら' getInstance() 'だけを呼び出すように各コンストラクタで' null'チェックを追加できます。 – 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; 
    } 

ちょうど ` .getInstance()`ときの呼び出しについて、彼は直後に自分の投稿を削除しても起動し、私のアイデアを与えた男..すべての答え

0

あなたがあなたのOPに実際に言っていることなくあなたの状態を述べているときには、循環参照の問題があります。

これを解決するためにSpringコンテナを使用することを検討できます。

関連する問題