java singleton pattern, should all variables be class variables?

rouble picture rouble · Nov 20, 2009 · Viewed 8.5k times · Source

If a class implements a singleton pattern, should all the variables be declared static?

Is there any reason they shouldn't be declared static? Does it make a difference?

Answer

Nader Shirazie picture Nader Shirazie · Nov 20, 2009

No. The singleton pattern just means that a single instance is the only instance -- it does not mean "make everything statically accessible".

The singleton pattern gives you all the benefits of a "single instance", without sacrificing the ability to test and refactor your code.

Edit:

The point I'm trying to make is that there is a difference between how functionality should be consumed (which depends on context), and how functionality should be initialized.

It may be appropriate that in most cases your object will only ever have a single instance (for example, in your final production system). But there are also other contexts (like testing) that are made much more difficult if you force it to be the only choice.

Also, making something static has more significant implications than just "only one instance of my class should be accessible" -- which is usually the intention.

Further, in software I've worked on, the initialization and lifecycle of objects is often controlled by someone else (I'm talking about DI here) -- and making something static really doesn't help here.