Singleton Pattern

Sometimes you create a class and the problem requires that it only be instantiated once. That is, you need to guarantee that there will be only one object of this type in your system.

Suppose, for example that the following class should be a singleton.

class Player  
{	public boolean play() 
	{ 	... 
		return true; 
	} 

	public String toString() { return "Player "; } 
} 

We can achieve this with a private constructor and a public static constant data member.

class Player extends Instruction 
{	public boolean play() 
	{ 	... 
		return true; 
	} 

	public String toString() { return "Player "; } 

	private Player(){} // prevent construction from outside.

	public static final Player instance = new Player(); // Legal from inside.
} 

Now you can't create new player objects, but you have access to (but cannot change) Player.instance.

Note, however, that an inner class in Java can't have a static field. There would be no way to prevent an outer class from calling even a private constructor in any case. Therefore, this can't be used in Java with inner classes.

For more in this pattern see: Grand Patterns in Java, Volume 1, Wiley, 1998.