Singleton Toni
Singleton Toni
Toni Sellarès
Universitat de Girona
Singleton: motivation
• Singleton: How to instantiate just one object - one and only one!
• Why?
– Many objects we need only one of: dialog boxes, objects that handle preferences and
registry settings, etc.
• Alternatives:
• Downside: assign an object to a global variable then that object might be created when
application begins. If application never ends up using it and object is resource intensive:
waste!
• Downside: how do you prevent creation of more than one class object?
Singleton: solution (1)
if (uniqueInstance == null) {
uniqueInstance = new Singleton ( );
}
return uniqueInstance;
private Singleton ( ) { }
Summary
• The Singleton Pattern ensures you have at most one instance of a class in your
application
• The Singleton Pattern also provides a global access point to that instance.
• Java’s implementation of the Singleton Pattern makes use of a private
constructor, a static method combined with a static variable
• Examine your performance and resource constraints and carefully choose an
appropriate Singleton implementation for multi-threaded applications.
• Beware of double-checked locking implementation: it is not thread-safe pre
JDK 1.5
• Be careful if you are using multiple class loaders: this can defeat the purpose of
the Singleton implementation
• If you are using a JVM earlier than 1.2, you’ll need to create a registry of
Singletons to defeat the garbage collector.