Pattern:
Singleton


Author

Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides

Intent

"Ensure a class only has one instance, and provide a global point of access to it." (Gamma, E., R. Helm, R. Johnson, and J. Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Reading, MA: Addison-Wesley, 1995)

Motivation

It is important for some classes to have exactly one instance. Although there can be many printers in a system, there should be only one printer spooler. There should be only one file system and one window manager. A digital filter will have one A/D converter. An accounting system will be dedicated to serving one company. To ensure a class has only one instance and that the instance is easily accessible, a global variable could be used, but it doesnt keep you from instantiating multiple objects. A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instance can be created (by intercepting requests to create new objects), and it can provide a way to access the instance. This is the Singleton pattern.

Known Uses

A subtle example is the relationship between classes and metaclasses (the class of a class). Each metaclass has one instance and keeps track of their sole instance and will not normally create another. The InterViews user interface toolkit uses this pattern to access the unique instance of its Session and WidgetKit classes, as well as others. (Linton, M., P. Calder, J. Interrante, S. Tang, and J. Vlissides. InterViews Reference Manual. CSL, Standard University, 3.1 edition, 1992.)

See Also

Abstract Factory, Builder, and Prototype patterns

Thumbnail

Keywords

Abstract Factory pattern, Builder pattern, Prototype pattern, Singleton pattern, creational patterns, Gamma patterns, object creation, global access, encapsulation (sole class instance), controlled instance access

Business Domains

any system requiring control over object instancing

Problem Forces

must control number of instances of a class

Benefits

provides control to single or multiple instancesreduces the global name space

Implementation Files

Test driver Test.javaSimple implementation of the pattern. Singleton.javaTest driver testsingleton.cppSimple implementation of the pattern. singleton.h



Generated on Fri Oct 20 10:49:03 GMT+02:00 2000 by Framework Studio