Static Reference to Self


public class A {

   public static A current;

   public A() {
      current = this;
   }
}

I’m considering doing something like the above and was wondering if this kind of thing is frowned upon and why. The reason i’m doing it is because I know there will only ever be one instance of the class A for each instance of my program and almost all classes need to be able to interact with the instance of class A. So I figured this would be a simpler approach than creating all the other classes with a pointer to the only instance of class A.

Thanks for any help,
Nathan

Why not make the whole class (methods and fields) static. The constructor can either be a static block or an initializer method if you need parameters.

This scenario is exactly why the Singleton design pattern exists.

That’s called a Singleton. There’s room for a lot of opinions on their usefulness, but if you’re going to use one, I recommend doing it right. First, don’t put the singleton logic in the constructor, period. In fact, the constructor has to be private if you’re going to prevent new instances from being created. Second, there’s all kinds of funky wrinkles involved if you’re ever going to access your singleton in multiple threads. But last, there’s a really easy way to make a singleton: make it an Enum

Exactly what Sproingie and BurntPizza said

You’d want something like maybe? I am not sure if its better to new in getInstance or at beginning of declaration

public class A{
        private static A instance = null;
 
        private A() {       }
 
        public static synchronized A getInstance() {
                if (instance == null) {
                        instance = new A();
                }
                return instance;
        }
}

I am not 100% sure if it has to be synchronized? Someone more qualified can answer that

Anytime you need an acces of your singleton you’d just do

A someAAccessor = A.getInstance();

Or alternatively, you could just make everything static and access them directly without ever creating an instance

It has to be synchronized if you use it from multiple threads, which you should pretty much assume you always do unless you make things explicitly thread-local.

Thanks for all the quick responses. I’ll look into the singleton pattern.

Out of curiosity do you use the singleton pattern for your primary class for your games?

Thanks,
Nathan

Why don’t you just store it in a global variable so you don’t end up designing a class so only one instance of it can exist? It could save you some design head-aches later - and maybe (probably) even some arguments with other programmers.

Singletons are highly controversial, global variables aren’t (as controversial) - stressing the ‘as’ as subjective though. My perspective is while you do have a lot of the negatives that come with singletons come along with globals, at least it doesn’t encourage you to design that class as if it is the only one that exists.

Optimally though, it would be better to pass the object around rather than store it globally. It makes it more difficult to extract code etc. Even if you think you’ll only ever have one instance.

Personally, I avoid singletons.

I would say that it is the other way around, there is more controversy about global state aka variables than having only a single instance of a class. On one hand using only a single instance of some class is a very common thing(webserver session data, thread pools …). On the other having something mutable in global space(accessible from everywhere) is frowned upon.

So why shouldn’t one just put stuff in the global space, it makes stuff so much easier right?
The thing is that global state is bad in many ways. Everywhere you use it in your code you get a hidden dependency to it. This will make debugging harder, can produce some nasty bugs(hard to find) and make it harder to split your app into modular parts.

The thing is with using global state, that it doesn’t scale. If you really only plan to have only 1 or 2 global variables in a little app, it might be justifiable. On the other hand if your app is growing and your use of global state is growing also, at some point you will loose the oversight on things and adding or changing little things will get extremely difficult.

Which brings us back to the famous Singleton pattern, which should really be called Globalton pattern. This is because implementations use a global object to provide a single instance, which can have the same problems as above.

As a final note, don’t do anything complicated stuff like your constructor thing or that getInstance method with null check. Just create your simple class which should be a Singleton any then create a final static instance of it somewhere else(NOT in the same class). This somewhere else could be the place where you store other constants for your game.

Yes. Soundsystem, gamemanagers, everything that I need access globally. Though sometimes I use static.

IMO there is almost never a point in doing lazy initialization of a singleton, unless you have lots of other static methods / fields in that class (in which case look at the inner class loading solution). If the only static call you ever make is getInstance(), lazy initialization is pointless. Using eager initialization ensures that the instance is created safely because class loading is thread safe, while meaning you don’t have to synchronize every access to getInstance().

ie.

public class A{
        private final static A INSTANCE = new A();
 
        private A() {       }
 
        public static A getInstance() {
                return INSTANCE;
        }
}

Singletons are over-used, but used sparingly they beat static methods. Not only can you implement interfaces, but you could also make the class A above abstract. That way you can easily swap in different implementations of A as required (testing, single / multi user, OS, etc.) - similar to what AWT’s Toolkit.getDefaultToolkit() does.

[quote]IMO there is almost never a point in doing lazy initialization of a singleton
[/quote]
… or for that matter, making them threadsafe. That is, until you do need it, and spend hours tearing your hair screaming “Y U NO WORK?!”

Seriously, it’s not hard to do it right. Use Guice, use lazy initialization holders, use an Enum, all those get singletons right. There’s just no good reason to do it half-assed when you know it’s going to bite you later.

Trying to work out whether that was meant as criticizing what I wrote or agreeing with it?! :-\

The code I wrote is thread safe, the same way as the lazy initializer holder - which is what I meant by “inner class loading” if you really need lazy initialization. Enum is also a good way to do it (still look weird to me) and deals with serialization - though if you’re serializing your singletons I’d guess you’ve probably got bigger problems! ;D

Sorry, I read the wrong piece of code and attributed it to you. :emo:

Problem with a static initializer that isn’t tucked away in an inner class is that you can’t have dependencies on other singletons reliably since you can’t guarantee that those have been initialized yet. Of course it doesn’t look very good even with the holder idiom, so once you have singletons that aren’t leaves on the object graph, you start looking at DI containers, and there’s an even deeper rabbit hole. :stuck_out_tongue:

Uh, isn’t the Java ClassLoader lazy? Shouldn’t that mean that the instance variable is initialized when the class is first used - that is, the same behavior as writing the singleton accessor lazily? I’m fairly certain that the ClassLoader loads classes as they are needed by the program, so the dependencies of the singleton should be loaded when it’s constructed - so at the same time that it is initialized.

The classloader may be lazy, but when the first use is in a static initializer, it effectively forces the whole graph, whereas inner classes are guaranteed initialized only on their first actual use within a method (though if you access it from a static initializer, you’re in the same boat again). Only likely to really bite you with circular dependencies, but those happen more often than you think if you’re ever prone to create a global “context” object statically then have classes that also use it statically to connect to another singleton. All in all it’s another reason to avoid static global singletons in the first place.

That was exactly my point! Maybe I didn’t word it well. Lazy singleton initialization only has different semantics to eager initialization if you have other public static fields and/or methods that are accessed first. I prefer the singleton being the only static and anything else being instance fields / methods - far less hassle and as you say the class loader itself is lazy and handles synchronization for you.

I get the feeling some people don’t realise that the singleton isn’t initialized until the class is actually used, so they go out of there way to create it lazily when they don’t need to - point I was addressing in changing the above code.

All the better to have the context object be the only singleton and all other objects be got from it wherever possible!

At which point you’re well on your way to reinventing your own DI container, and you should probably look at Guice or Dagger or PicoContainer. Not that I’m religious about DI/IOC: I’ve got a few singletons sprinkled through my code that don’t use any such thing, but they’re straight up values, no collaboration going on.