Ich habe zwei Singleton in meiner Anwendung und hier ist mein Problem: Jeder von ihnen braucht einander, also kann ich keine der beiden bauen, weil ich werde ein StackOverflowError. Wie komme ich darüber hinweg?So erstellen Sie eine Eins-zu-Eins-Singleton-Beziehung
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 Jungs! :)
Wie wäre es nur anrufen ' .getInstance()', wenn Sie brauche ich die Instanz der anderen Klasse, anstatt sie in einem Feld zu speichern? –
Weil ich die Methode sehr oft rufe und ich denke, dass der Code auf diese Weise weniger lesbar wäre. Ich bin mir ziemlich sicher, dass es ein Weg sein muss, es so zu machen – Antoine
Sie können in jedem Konstruktor eine 'Null'-Prüfung hinzufügen, um' getInstance() 'nur aufzurufen, wenn der Verweis auf das andere Singletone' null' ist. – Titus