Consider where you think you have an object that represents a single thing. Like the keyboard. You have two options - you can make all the methods to deal with the keyboard class methods. After all there is only one and what sense does it make to have programmers allocating Keyboards willy nilly? So you make all the methods class methods and the class object itself represents THE keyboard.
This sounds great - until USB arrives and you want to write a two player game letting each player have his own keyboard. Now you've got potentially several keyboards and the keyboard class you wrote is junk - you can't use it.
So we hedge our bets - we actually create a keyboard class but put all the behavior on the instance side. Then we make the class responsible for determining how many keyboards there can be and what the allocation policy is. For conventional single keyboard apps you implement singleton. There is exactly one instance of the Keyboard and you ask the class for it.
In Java this looks like this:
public class Keyboard
{
// make the constructor private - only the class can call it
private Keyboard() { ... }
// keep a copy of the singleton
static _instance;
// provide a way to get the singleton - construct only if asked for
public static instance()
{
if(null == _instance) _instance = new Keyboard();
return _instance;
}
...
}
When you get to your game, you only have to tweak the class a little like:
private Keyboard
{
Keyboard _player1();
Keyboard _player2();
public static Keyboard player1()
{
if(null == _player1) blah blah blah
}
you get the idea. You use the class to control how many instances of a class exist.
The problem I alluded to is that - with the class instance variable being the only reference to the object, and the object being the only reference to the class, the GC concluded nobody else would care if the thing went away. This is basically true - but one win to singletons is you initialize them once and they sit there all warmed up and ready to use. Collecting the class caused a lot of thrashing of initialization code.
Stupid Java people.