- Ensure that only one instance of a class is created
- Provide a global point of access to the object
- Allow multiple instances in the future without affecting a singleton class's clients
Below example shows how to create a singleton object. A singleton is a class of which there can only be one instance in the same Java Virtual Machine.
To create a singleton there has to be a private constructor because the class will itself control the one and only instance that will be created, and of course a private constructor cannot be called from outside the class.
Instead, a method is created with public access that returns the singleton instance (if the method is called the first time the object is instantiated). The example class MySingleton illustrates this:
/**
* MySingleton.java
*
* @author www.javadb.com
*/
public class MySingleton {
//the static singleton object
private static MySingleton theObject;
/**
* private constructor
*/
private MySingleton() {
}
/**
* Checks if the singleton object is created or not,
* if not it creates the object and then the object is
* returned.
*
* @return the singleton object
*/
public static MySingleton createMySingleton() {
if (theObject == null)
theObject = new MySingleton();
return theObject;
}
}
No matter how many times the method createMySingleton() is called, it will always return a reference to the same singleton object.
This code illustrates this by calling the method twice and then compare the two references. The output of the code is 'true' since they both point to the same singleton object.
No comments:
Post a Comment