Singleton Pattern

If a system only needs one instance of a class, and that instance needs to be accessible in many different parts of a system, you control both instantiation and access by making that class a singleton.


Often, a system only needs to create one instance of a class, and that instance will be accessed throughout the program. Examples would include objects needed for logging, communication, database access, etc. You could pass such an instance from method to method, or assign it to each object in the system. However, this adds a lot of unnecessary complexity.

Or, you could make that single instance the responsibility of the class, and then query the class for the instance.

Therefore, let the class create and manage the single instance of itself, the Singleton. Wherever in the system you need access to this single instance, query the class.

Simply put,

Ensure a class has only one instance, and provide a global point of access to it.

Resulting context

This unifies access (cf. NarrowTheInterface) to the singleton, leaving parts of the system uninterested in the singleton unaffected by it. Further, because access is controlled by a class, that class method can include additional logic needed to handle these queries.

Singletons are most appropriate for services that do not change their nature based on their invocation context. A singleton can be created at startup based on context or be reset for larger scale state transitions. A lot of things fall into this category: logging, communication, database access, etc are candidates. (Most things, of course, do not fall into this category.)

Simply put,

Singletons make it easy to compose a program from different components.

Singletons do not create unnatural interdependencies made by passing a context object around, where every piece of code will bind to everything in the context object. Singletons stand alone.


But aren't Singletons just global variables?

Singletons are very similar to GlobalVariables, and are often implemented with global variables, even if they masquerade as class members.

The difference between the two is subtle. For one thing, because singleton access is managed by a class method, you can add additional logic to that method. More abstractly, the point of a singleton is to ensure that a class has only one instance (strictly speaking this is not true, according to the GoF book a singleton could return instances from a pool, and because you have to go through the getInstance() method you wouldn't have to worry about it -though in some case you will most definitely know it-. This is stated as being one of the benefits of the singleton in the GoF book). SingletonPattern has to do with how to limit instances, while GlobalVariables are more related to how programmers declare instances.

Nonetheless, singletons have problems similar to globals; e.g., creating dependencies in vastly separated parts of the system, so side effects can appear far afield from their causes. Often singletons are abused by inexperienced programmers who think that the use of the pattern will magically solve all the problems associated with GlobalVariables. (See SingletonGlobalProblems for more.)


Creational logic

The power of the Singleton goes beyond just controlling the instance count. As mentioned above, because access is controlled through a method, you can add additional logic behind them. In particular, aside from synchronizing or controlling access, one can control when singletons are created, in many languages not possible for global variables. In C++, for example, singletons are often used when globals in different modules must be instantiated in a particular order; otherwise, you are at the mercy of the linker. An alternative way to do this is LazyInstantiationPattern.

Other examples: You could easily synchronize access to the singleton, as Microsoft COM can through its apartment threading model. You could make singletons that are "one per thread" instead of "one per process" by using ThreadLocalStorage. You could even limit access to those with the right security privileges.

For an expensive singleton that isn't necessarily needed, another powerful idiom is to create the singleton the first time it is used. Also this idiom is beneficial when you have singletons representing different hardware, like graphics cards, that will not be simultaneously present in the local machine. In particular, you get to instantiate the singleton after you have enough information to specialize it.


Polymorphism

More powerfully, consider a service as defined by an abstract interface. Any component can insert itself as the singleton. This component can be created using a factory or a link time decision. Anyone who ever needs that service only has to access the singleton for the service. Very simple. Very flexible.

Creating a singleton representing the graphics card is a good example of this. Each machine is likely to have only one graphics card (that you're interested in), but you may want to support more than one card in your application. This way you instantiate only the graphics card that you need, yet access all of them through one universal interface.

Testing

We can use this idiom for testing as well. In a test environment we don't want to worry about complex startup issues or about complex dependencies between subsystems. If all access to a subsystem goes through a singleton representing it (maybe a la FacadePattern), you can easily replace that singleton with a MockObject for testing--really, a mock system. Think of this as rolling your own dynamic linking. Here's an anecdote:

If there's a Logger base class I'll create a LoggerService to access a logger singleton. Every access to the logger service goes through LoggerService. The loggers can be individually used and tested. We have different loggers for different systems. We have different loggers that are installed in different states because often the startup environment is very feature poor and requires a different sort of logger than later when we have the full OS and TCP stack available. Nobody knows anything about all this because they only ever see a logger service. --anon.


A Singleton is the combination of two essential properties:
  1. Ensure a class only has one instance
  2. Provide a global point of access to it
The first property is nearly always overspecification. It might be useful in cases where object identity comparisons are important, for example, the cumbersome EnumeratedTypesInJava. But in most cases you gain nothing from such a property, and you always pay a price in flexibility.

What do you do if there truly is only one instance of something physical -- e.g. a camera, a sensor -- that has state? Singletons ensure that there is exactly one interface to unique system resources. All of these entities are shared resources that everything in an application can use, while nothing in the application "owns" them.

What if you add a second camera?

''Luckily, you thought about that ahead of time and implemented a CameraPool? singleton, that manages all of the available cameras.

> Luckily, you thought about that ahead of time and implemented a CameraPool? singleton, that manages all of the available cameras.

And what if you never end up adding additional cameras? In that case your code has been overly complex for no reason and you are suffering from a case of SpeculativeGenerality.


Singletons are not evil, but they can be abused. One way to reduce side-effects is to separate the interface of the object from its singleton property. Otherwise your singleton is doing two jobs, which is bad OO.

For example, you can have an abstract interface for a singleton object's method, plus a means of setting the singleton up during initialization. So you can use different behaviors for the singleton for testing and other purposes. Now, this isn't a standard self-constructing singleton, but you can write the instance function so that it constructs a default object if one has not already been supplied.

You can also make your production code talk to a Registry which manages the singletons, without the managed objects needing to know or care if there is one instance or many. A Registry also makes it easier to insert unloading & reloading functionality for hot-swapping of singletons if it becomes necessary later.

You UnitTest the objects which implement the interface normally, not worrying about their singleton property. UnitTests of objects which use the singleton property are initialized to use a test implementation of the interface. The truly TestInfected can write a UnitTest for the code which initializes the singleton.


This was a big problem on a system we wrote a few years ago. Since then we have been very conscious of making sure that singletons are constructed and destructed in the right order. What we do is construct all of our singletons in the main line as standard objects on the stack. This guarantees the order of construction and destruction. In addition, if one singleton depends on another, we pass a reference to this singleton into the constructor of the singleton who depends on it. (It is passed in as a dummy argument that is not actually used in the implementation.) This guarantees that they are constructed in the right order in the main line and documents any dependencies that exist.

Every singleton class is done as an abstract base class and the actual objects constructed in the main line are instances of particular derived classes. This allows different client systems to choose different implementations (or even provide their own) for the various singletons. And, of course, this also works for the unit tests where you want a specific implementation that you can use for testing other code.

Note that the base class constructor is responsible for setting the static "instance" data member to "this" and the destructor resets it to 0. An assert is used to make sure that the instance exists when calls are made to it.

-- JamesCrawford


The singleton serves as a replacement for global variables and global functions that act on them. It preserves the restriction that there can only be one instance of the class -- the main reason for the global approach -- while allowing you to treat that instance as just another object.

You could use a global object, but if you wanted to have more than one of the object in the future you'd have to explicitly change every reference to that object in your code. If the global characteristic is hidden behind a singleton you only have to change it in one place. It's an essentially difficult change to make for other reasons, so the singleton will make that change easier, but not necessarily easy.

A ContextObject is an attractive way to package Singletons. A Context is mostly something that lets you find the appropriate other things: "Semi-formal? Now I know to wear a tie." "This Graphics object? Now I know to draw there." "That's the current directory? Now I know where to start looking for files."

So you could also put the Singleton instance in some well-known but relatively local object that the caller knows how to find. E.g.:
 parent.getContext().getLogInstance().log("I will not waste chalk.");
This has the advantage that it insulates the ultimate caller from the decision to make only a single instance of the Singleton class, thus making the caller more reusable. Specifically, the caller needs no changes when you change the system to use multiple instances of the (now grossly misnamed) Singleton class.

Perhaps Singleton should be viewed as a wrapper around the class that actually does the work. It's just an accident that we have to put the single-instance-enforcement code in the very same class that does the work (in order to make the constructor private). Then you can simply "unwrap" the working class if you decide to have multiple (or a fixed number of) instances.

In the example above, your context looks like a ServiceLocator to me. Could you explain the difference? -- LarsStitz?


Not using singletons causes other sorts of smells. Without them you must centralize the creation of objects in one place and wire them all up correctly. This centralizes everything and makes it difficult to bring in new components without having to modify the GodCode.

If you have three singletons you want to convert to regular objects, you do not have to create them all in the same place. If you have only one singleton that you want to replace, it does get created someplace, but so does everything. -- MichaelFeathers


Does the SingletonPattern violate YouArentGonnaNeedIt? If I need more logs/database managers/properties or other global things, I can always add them later - at some cost, but it may save me cost as well just sticking to Java static methods at the moment. Any opinions? -- ArieVanDeursen

Funny; I tend to think that eliminating singletons violates YouArentGonnaNeedIt: I tend to think of singletons and static methods as objects that haven't developed enough to be split out into an independent class. Eventually the static methods and variables of a (C++) class get so messy that I say "darn, this really needs to be its own class" - so I split it off.

If I start something as a Singleton pattern, it helps me upgrade it to a "real class" (with multiple instances) later, because I can gradually change "global references" with parameters that pass the instance around. In fact, I happen to be doing this with several global singleton objects on my current project (early 2001): I say "gosh, I really dislike the fact that this low level function references the global singleton; I think I'll make it a parameter. --> There, that looks better." Eventually, we'll probably support multiple workspaces being open at one time; we're thinking about it. -- JeffGrigg


Since then, we have been very conscious of making sure that singletons are constructed and destructed.

System startup and destruction are larger problems than singletons, especially when you have highly threaded systems that have variable startups times and have dependencies among each other. If you solve this problem properly the singleton construction order is not a problem.


Singletons should be used to control creation, not access. A Singleton should not be used as a global object just because "you can". Using a Singleton as a global access point violates the LawOfDemeter.

Ask yourself: "Would it be fundamentally wrong to have a second instance of this class in the system?". Sometimes it would, but sometimes you'll find that you were just trying to get a global variable with a rubber nose.

And maybe the Singleton getInstance() method should only be invoked once in the whole codebase. This way you can only get the Singleton once, and then you pass it around as you would with any other object. This has the effect of enforcing the architecture of the system in the code.

Passing around a singleton reference forces the programmer to ScopeContextProperly?, and is often found in frameworks to control coupling dependencies. Examples of AllowClientToSetContext? can be found throughout the standard Java packages whenever there exists a setter for the singleton instance of a factory class. These ideas work together to help prevent GlobalVariableCoupling?.

Most client code of the singleton doesn't care where the singleton comes from - it just wants to use it. But just because it is single instance doesn't mean you need to get it from a single place.

Sounds like a ContextObject. Personally, I think my context object is the global program name space. There's no need to duplicate another. Creating a context object unnecessarily binds service access points together. Any new service causes a change in this object that will not be needed by a large percentage of the other objects.

If we use a ContextObject that is passed around everywhere, isn't that a CodeSmell? This ContextObject totally binds the program together linking parts that have nothing to do with each other. If you need a new part of context you have to add it to the context object which makes every other part of the code see it and require it when they don't need it. Very smelly. With a singleton you can easily compose a program of independent components because they only ever use what they need.


Much fuss has been made over how singletons can enforce their singleness, which is much fuss for little gain.

Here's a very simple implementation of a singleton FooBar object:

  FooBar globalFooBar;  // Don't create any other instances!!!

(The "singletonness" of this object is enforced by humans: If you create your own instances, the system won't work right, and your project's technical lead will slap you upside the head. ;-)

Singletons have one main advantage over this approach. You only create a singleton object if your program execution uses it. Besides, singletons are the logical way to simulate global variables in Java.


Moved from SingletonsAreEvil

Without the pressure of testing, though, we would never have found those improvements. And all because of that dang Singleton... -- Kent

I don't understand the problem here. The simplest thing worked. Then it no longer worked, so you changed it. If the interface was good in the first place, the change should have been trivial. Isn't this supposed to be how it works? Isn't this refactoring? Calling singletons evil because your requirements changed means there is a lot of evil in the world. It should have been trivially obvious that a singleton is not the way to go when your data sets change with every invocation. If the singleton was a strategy object which was passed a data set that might have worked. Again don't make singletons out as the bad guy when your design was seriously flawed to begin with. -- AnonymousDonor


My take is this: The system I program for is embedded, ie. it has and can only have one screen, it has and can only have only keyboard, etc. Don't singletons work perfectly in these cases?

We have very little memory, and most memory shuffling (aka realloc(), etc) causes severe fragmentation. Because of this, most of our lists are merely pointer-lists with their nodes allocated from a global pool. One such list is our messaging system lists which all of our objects rely on. Because this pool is allocated at runtime, it happens after global object construction takes place. Any globals we would have had are rendered useless which also makes the Singleton pattern extremely useful. -- MichaelAbbott


Singleton is a social disease. Because Singleton is so easy to understand, it is the single pattern that almost anybody who merely thumbed through GoF at the bookstore can remember and explain. That leads to unwarranted exuberance for the pattern among those who can least afford such exuberence.


I would always promote Singletons as a very pragmatic approach to resource allocation. However, using a Singleton is an implementation decision which should not affect the interface of the given class. I would advise to This means, instead of
  ResourceHolder rh = ResourceHolder.getInstance();
where ResourceHolder would be a concrete implementation class with a static factory method, you would have
  ResourceHolder rh = getResourceHolderFactory().getResourceHolder();
where the ResourceHolderFactory was set by DependencyInjection and ResourceHolder itself is an abstract interface. Et voila, you have the advantages of the SingletonPattern and the flexibility of decoupling at the same time. This means in fact introducing the overhead of DependencyInjection, but that will be the point where decoupling takes place.

-- LarsStitz?


Now, we manage the dependencies between packages fairly strictly so that it is very clear which other packages a package is allowed to use (and thus which singletons). But we don't do XP - the structure of the system is determined during high level design. Perhaps in an environment where the structure evolves it is too easy to add an inappropriate dependency on a singleton.

-- JamesCrawford

These aren't XP projects where I've seen the problems with Singleton. If you write lots of unit tests, you quickly get away from global variables, even for stuff that seems global. -- KentBeck

You pretty much live with the fact that you can only have a single instance, in process, of the code that depends on the singleton. Consequently, writing UnitTests becomes painful. -- MichaelFeathers


They can be a real boat anchor on an app if they have state. Whole sections of the code can't be spun off into different threads. -- MichaelFeathers

It is possible (though not necessarily easy) to use SingletonPattern with threads. That is, to have a single "globally accessible" object per thread, instead of one per process. Use ThreadLocalStorage. -- JeffGrigg

One more point: some Singletons can induce a tremendous drag on concurrency in heavily-loaded systems. (Java folks, to see an example, profile your Oracle JDBC driver under heavy load from several threads.) Watching all your threads queue up waiting for their turn to use a shared resource is no fun.

I am from the world of embedded systems. In my world there are things which only exist once. The point of using a singleton is exactly to make sure, that the state which describes these one time only things also exists only once. Of course this will block concurrency. But the reason is that these one time only things cannot be used concurrently; so this is not a problem of the singleton pattern, it is a constraint placed upon you by the physical realities of your system. What happens if your system writes to a GLOBAL log file ? To me it seems a singleton perfectly models the access to such a global log file. -- Ingo Rohloff
A Singleton is singular to a particular domain. Most of the problems with using them appear to be problems trying to use the available implicit class scopes in architecturally richer environments e.g. distributed or context-variable. This leads me to avoid the implicit class scope forms of Singleton. No worries so far. -- RichardHenderson.

Not everything works in every environment and it is silly to criticize a technology as inferior solely because it is not best in every case. I have found that I use stateless singletons that implement some interface and get returned from within a factory. The user does not know they are using a singleton. I can change my mind later if I so choose and not use a singleton. The advantage is that my system does not do a massive amount of object creation and cleanup. I avoid static method classes since they do not work well with interfaces in Java. I tend to always strive to leave open the option to use an interface. -- JohnWright?


Singletons simulating global variables

An anti-pattern. You are very familiar with global variables and have no problems with them. You want the ability to invoke methods on some particular objects from any other class but you don't want any accessors or navigation. You add another Singleton. Pretty soon there are tons of Singletons lying around. -- HafizAhsan

What is your alternate strategy? What are its downsides? What makes you like those downsides better?


A common complaint about Singletons (found here too) is that the one class has two functions: Was the current implementation chosen because namespaces were not yet popular when the GOF book was written? Java and packages weren't around either.

Seems to me, it should be possible to put two distinct classes in the same namespace (or package) exclusively and get the same behavior without the aforesaid problem.

Basically, PrintDriverInstanceController?.getDriverInstance() would return a PrinterDriver? instance. PrinterDriver? would not have a private constructor. Instead, it would be constructable only from within the same namespace (package level access in Java). PrinterDriverInstanceController? would be an extreme case of a Factory object and would be in the same namespace as PrinterDriver?.

I am eager to get responses on this suggestion.

-- SriramGopalan


Maybe it's just me, but I am not following any part of your suggestion, beginning with (but not limited to): what "current implementation" are you talking about?


I am talking about the standard class diagram for the Singleton pattern in GOF book. Most implementations follow that rather blindly.

For example, let us say I want to implement a PrinterController?. It purpose is to control access to a series of printers and route print jobs. Further assume that I want only one instance of this class because the algorithms used in job routing depend on this object holding exclusive control over the printers.

Now, the standard implementation would be a class called PrinterController?. It would have a private constructor and a getInstance method to get the only instance.

What I am proposing is a package names com.mycompany.printercontroller. This package will have two classes - PCInstanceFactory and PrinterController?. PCInstanceFactory will have a class variable of type PrinterController? and the getInstance method which, in turn, uses the PrinterController?'s constructor. This constructor will be of package access, so only PCInstanceFactory will be able to invoke it.

What does this get us? It gives us clearer separation of concern. Each class has one clear mandate. One will control the number of instances of the other and the other will have the algorithms that deal with print job routing. Wouldn't that alleviate the concern? -- SriramGopalan

I've seen similar things. I've seen a lot of approaches to singletons; I wouldn't say most of them follow one approach.

The first problem I see with your proposal is that surely it is massive overkill to create a singleton factory for a single type of singleton, so that it can never be reused. Creating PCInstanceFactory just to create a single object of type PrinterController? is adding a lot of complexity to something that one would hope would be a simple problem.

I have the same criticism of Alexandrescu's approach in "Modern C++ Design" (although his singleton holder is at least reusable).

Ideally, simple problems should have simple solutions. Global variables are considered harmful, but if the alternative is 2,000 lines of singleton-related code per singleton instantiated, then the cure is worse than the disease.


H.N

My solution is create a private synchronized method.

	/**
	static public Singleton instance() {
	if(null == _instance) {
		instance_helper();
		System.out.println("CREATE NEW SYSTEM INSTANCE!!!!!!!!!!");		
	}else{
		System.out.println("REUSE THE SAME SYSTEM INSTANCE!!");
	}
	return _instance;
	}

/**
	static private synchronized Singleton instance_helper(){
	_instance = new Singleton();
	return _instance;
	}

Except it doesn't work. "_instance" can be null in the logic for multiple threads before instance_helper is called, leading to multiple instances being created. See DoubleCheckedLockingIsBroken.

H.N

How about putting a flag in synchronized method ?

	static private synchronized Singleton instance_helper(){
	if(flag){
		_instance = new Singleton();
	}
	flag = false;
	return _instance;
	}

Why not just create a static instance and let the class loader do your work for you? It's much easier to read and guarantees one instance per class loader.


The system I work on has a lot of singletons, and it suffers from several of the problems mentioned here, in SingletonsAreEvil, and in SingletonGlobalProblems. I am in the process of converting things to an arrangement (mentioned by JeffGrigg above, four years ago!) where these objects are passed as parameters instead being fetched from well-known locations. In typical operation (that is, not under testing) there will still be exactly one instance of each such object. Team members usually still refer to these objects as "singletons" even though they no longer fit SingletonPattern. Is there a need for a new term to describe objects for which there is only one instance, but which don't fit SingletonPattern? I've been trying to use the term "solo object" but this isn't very evocative.

-- StuartMarks 29 July 2005


I think Singleton discussion and conceptualization suffers from limiting the scope to the specific type of singleton discussed in DesignPatterns. In reality, singletons and similar structures are varied and they can be classified from several points of view.

Why do you want only one instance? Examples: What do you do to have only one instance? In increasing order of strictness and amount of machinery: What is the scope of the singleton instance? Examples: What is the lifecycle of the singleton instance? What has a single instance? Classes in a program and classes in its design need not be coincident. Conceptually we can take care to share and preserve instances of: The "traditional" SingletonPattern spans only a small part of these design variations: fearful avoidance of multiple instances (allowing for classes that don't support them), strict enforcement (which implies mistrust of client code), use of class variables and methods instead of more general mechanisms. Often SingletonsAreEvil in a specific context because these above choices are inappropriate and a good design would require some originality.

-- LorenzoGatti


References:

This is one of the GangOfFour DesignPatterns.

See also:

Implementation details by language:
JavaSingleton, CppSingleton, PerlSingleton, PhpSingleton, PythonSingleton, RubySingleton, SmalltalkSingletonProblem, VbClassicSingleton.

Applications:
ConnectionSingleton manages database connections.

Alternatives: Other issues:
SingletonsAreEvil, SingletonConsideredMisleadinglyNamed, ProducingSingletonGarbage, SingletonGlobalProblems, UnitTestingSingletons, SingletonRefactorings
Non-c2 references:
There was quite some discussion in FebruaryZeroSix about the SingletonPattern. Most of the following pages were created within one week. Some (most?) of these are probably redundant and should be merged when the topic cooles down:


See also: ReverseFlyweightPattern


CategoryPattern CategoryCreationalPatterns

EditText of this page (last edited April 3, 2010) or FindPage with title or text search