Code for the basic singleton pattern
Details:
This code shows the basic singleton pattern implemented in Java. Singletons allow you to have a single copy of an object seen by all the running code in the JVM (kinda - see more info, below*).
Original author/s: Andy Evans
Original location/s:
License: none
Other info: For more info, see Why are Singletons needed, and how do they solve the issue?. You can also find a nice exploration of the issues with Singletons on
Java World
(*including cases where there may be more than one singleton). Note that, as Josh highlighted after the
Singleton lecture, the definition of the
static Singleton variable at the start isn't recursive as it is creating a label, not an
object, also note that the constructor isn't recursive because
it doesn't call getInstance.
Imports and instance variables:
N/A
Code:
class Singleton { /** * This variable is key. This is going to be the only * copy of this class as an object in the whole code. * Remember, static objects are the only copy of something as they * are like variables associated with the class, not objects made from the * class. * You don't make any other new objects of this class elsewhere, * you just ask for this single object, wherever you need to use it. **/ private static Singleton singleton = null; private double value = 0.0; /** * The constructor is made private to stop * people making a new object from the class. **/ private Singleton () { } /** * Method returns the pre-existing static object, or makes it and returns it. **/ public static Singleton getInstance() { if (singleton == null) { singleton = new Singleton(); } return singleton; } public void setValue(double valueIn) { value = valueIn; } public double getValue() { return value; } } /** * Class to use singleton. **/ class User { public User() { method1(); method2(); } private void method1 () { Singleton s1 = Singleton.getInstance(); s1.setValue(23.42); } private void method2 () { Singleton s2 = Singleton.getInstance(); System.out.println(s2.getValue()); } public static void main (String args[]) { new User(); } }