A singleton is a class that is instantiated only once. This is
typically accomplished by creating a static field in the class
representing the class. A static method exists on the class to obtain
the instance of the class and is typically named something such as
getInstance(). The creation of the object referenced by the static field
can be done either when the class is initialized or the first time that
getInstance() is called. The singleton class typically has a private
constructor to prevent the singleton class from being instantiated via a
constructor. Rather, the instance of the singleton is obtained via the
static getInstance() method.
The SingletonExample class is an example of a typical singleton class. It contains a private static SingletonExample field. It has a private constructor so that the class can't be instantiated by outside classes. It has a public static getInstance() method that returns the one and only SingletonExample instance. If this instance doesn't already exist, the getInstance() method creates it. The SingletonExample class has a public sayHello() method that can be used to test the singleton.
The SingletonExample class is an example of a typical singleton class. It contains a private static SingletonExample field. It has a private constructor so that the class can't be instantiated by outside classes. It has a public static getInstance() method that returns the one and only SingletonExample instance. If this instance doesn't already exist, the getInstance() method creates it. The SingletonExample class has a public sayHello() method that can be used to test the singleton.
SingletonExample.java
package com.cakes; public class SingletonExample { private static SingletonExample singletonExample = null; private SingletonExample() { } public static SingletonExample getInstance() { if (singletonExample == null) { singletonExample = new SingletonExample(); } return singletonExample; } public void sayHello() { System.out.println("Hello"); } }The Demo class obtains a SingletonExample singleton class via the call to the static SingletonExample.getInstance(). We call the sayHello() method on the singleton class. Executing the Demo class outputs "Hello" to standard output.
Demo.java
package com.cakes; public class Demo { public static void main(String[] args) { SingletonExample singletonExample = SingletonExample.getInstance(); singletonExample.sayHello(); } }Singleton classes are a useful way of concentrating access to particular resources into a single class instance.
No comments:
Post a Comment