I am building a singleton service in Java for Android:
final class MyService {
private static Context context = null;
// ...
private MyService() {
myObj = new MyObj(context);
// ...
}
private static class Singleton {
private static final MyService INSTANCE = new MyService();
}
/**
* a singleton - do not use new(), use getInstance().
*/
static synchronized myService getInstance(Context c) {
if (context == null) context = c;
return Singleton.INSTANCE;
}
To improve performance I use static variables and methods throughout.
My questions:
for objects, new() ensures the opportunity to initialize that object before its use. Is there an equivalent for a static class? For example: when static methods depend upon earlier initializations - such as as for 'context' above - is there a means of ensuring that the initialization happens first? Must I throw an exception if they have not?
as this is all static I expect that there is only the class itself: is that a singleton by definition? Is the recommended code above just the way of preventing instantiation of objects?
Thanks in advance!