Dobry den,
chcel by som sa opytat, ci neexistuje nejaky elegantny workaround, ked vytvaram singleton, ktory v konstruktore vytvara class uz volajuci dany singleton. Nieco taketo:
class Singleton{
private Singleton INSTANCE;
private Object obj;
private ClassUsingSingleton classUsingSingleton;
private Singleton(){
obj = new Object();
classUsingSingleton = new ClassUsingSingleton();
}
public Singleton getInstance(){
if(INSTANCE==null){
INSTANCE = new Singleton();
}
return INSTANCE;
}
public Object getObject{
return obj;
}
}
class ClassUsingSingleton{
final Object singletonObj;
public ClassUsingSingleton(){
singletonObj = Singleton.getInstance().getObject(); // Toto nieje
// bude sa to volat do nekonecna, lebo pointer na INSTANCE je zatial null
}
}
Alebo to ide len poslat do kostruktora, prip. ak by tam nebolo final, pouzit metodu na vytvorenie tohto classu:
class Singleton{
// kod
private Singleton(){
obj = ...
classUsingSingleton = new ClassUsingSingleton(obj);
}
//resp.
private Singleton(){
obj = new Object();
}
public void createClassesUsingSingletonInConstuctor(){
// ako v predoslom priklade
classUsingSingleton = new ClassUsingSingleton();
}
//kod
//
}
Jo a s enumom je to to iste, pokial nieje vytvoreny neda sa pouzivat.