| Java, Eclipse and Web programming Tutorials |
Version 0.2
Copyright © 2009 Lars Vogel
09.08.2009
| Revision History | ||
|---|---|---|
| Revision 0.1 | 01.07.2009 | Lars Vogel |
| Separated from http://www.vogella.de/articles/DesignPatterns/article.html | ||
| Revision 0.2 | 09.08.2009 | Lars Vogel |
| Reworked | ||
Table of Contents
The singleton Pattern ensures a class has only one instance, and provides a global point of access to it.
Singletons are useful to define classes which should only be available once, e.g. a model which is use in several view of an application, a logger or a device driver.
An example is an application which reads the data from a file into another class A. This content should be available in the whole application. Therefore the class A is defined as a singleton.
Another example would be the following View A and View B would like to display the same data of class with hold the data (model class). Using a singleton for the model class ensures that same data is used.
The possible implementation of Java depends on the version of Java you are using.
As of Java 6 you can singletons with a single-element enum type.
package mypackage;
public enum MyEnumSingleton {
INSTANCE;
// other useful methods here
}
Before Java 1.6 a class which should be a singleton can be defined like the following.
public class Singleton {
private static Singleton uniqInstance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (uniqInstance == null) {
uniqInstance = new Singleton();
}
return uniqInstance;
}
// other useful methods here
}
A static class with static method would result in the same functionality as a singleton. As singletons are define using an object orientated approach it is in general adviced to work with singletons.
Singleton violate the "One Class, one responsibility" principle as they are used to manage its one instance and the functionality of the class.
A singleton cannot be subclassed as the constructor is declared private.
If you are using multiple classloaders then several instances of the singleton can get created.
For questions and discussion around this article please use the www.vogella.de Google Group. Also if you note an error in this article please post the error and if possible the correction to the Group.
I believe the following is a very good guideline for asking questions in general and also for the Google group How To Ask Questions The Smart Way.