496
votes

The glorified global variable - becomes a gloried global class. Some say breaking object-oriented design.

Give me scenarios, other than the good old logger where it makes sense to use the singleton.

21
Since learning erlang, i prefer that approach, namely immutability and message passing.Setori
What isn't constructive about this question? I see constructive answering below.mk12
A dependency injection framework is a very complex singleton that gives out object….Ian Ringrose
Singleton can be used as a manager object between the instances of other objects, thus there should be only one instance of the singleton where each other instances should communicate via the singleton instance.Levent Divilioglu
I have a side question: any Singleton implementation can also be implemented using a "static" class (with a "factory"/"init" method) - without actually creating an instance of a class (you could say that a static class is a kind-of Singleton implementation, but...) - why should one use an actual Singleton (a single class instance that makes sure its single) instead of a static class? The only reason I can think of is maybe for "semantics", but even in that sense, Singleton use cases doesn't really require a "class->instance" relationship by definition... so... why?Yuval A.

21 Answers

376
votes

On my quest for the truth I discovered that there are actually very few "acceptable" reasons to use a Singleton.

One reason that tends to come up over and over again on the internets is that of a "logging" class (which you mentioned). In this case, a Singleton can be used instead of a single instance of a class because a logging class usually needs to be used over and over again ad nauseam by every class in a project. If every class uses this logging class, dependency injection becomes cumbersome.

Logging is a specific example of an "acceptable" Singleton because it doesn't affect the execution of your code. Disable logging, code execution remains the same. Enable it, same same. Misko puts it in the following way in Root Cause of Singletons, "The information here flows one way: From your application into the logger. Even though loggers are global state, since no information flows from loggers into your application, loggers are acceptable."

I'm sure there are other valid reasons as well. Alex Miller, in "Patterns I Hate", talks of service locators and client side UI's also being possibly "acceptable" choices.

Read more at Singleton I love you, but you're bringing me down.

134
votes

A Singleton candidate must satisfy three requirements:

  • controls concurrent access to a shared resource.
  • access to the resource will be requested from multiple, disparate parts of the system.
  • there can be only one object.

If your proposed Singleton has only one or two of these requirements, a redesign is almost always the correct option.

For example, a printer spooler is unlikely to be called from more than one place (the Print menu), so you can use mutexes to solve the concurrent access problem.

A simple logger is the most obvious example of a possibly-valid Singleton, but this can change with more complex logging schemes.

51
votes

Reading configuration files that should only be read at startup time and encapsulating them in a Singleton.

39
votes

You use a singleton when you need to manage a shared resource. For instance a printer spooler. Your application should only have a single instance of the spooler in order to avoid conflicting request for the same resource.

Or a database connection or a file manager etc.

26
votes

Read only singletons storing some global state (user language, help filepath, application path) are reasonable. Be carefull of using singletons to control business logic - single almost always ends up being multiple

20
votes

Managing a connection (or a pool of connections) to a database.

I would use it also to retrieve and store informations on external configuration files.

12
votes

A singleton should be used when managing access to a resource which is shared by the entire application, and it would be destructive to potentially have multiple instances of the same class. Making sure that access to shared resources thread safe is one very good example of where this kind of pattern can be vital.

When using Singletons, you should make sure that you're not accidentally concealing dependencies. Ideally, the singletons (like most static variables in an application) be set up during the execution of your initialization code for the application (static void Main() for C# executables, static void main() for java executables) and then passed in to all other classes that are instantiated which require it. This helps you maintain testability.

11
votes

One of the ways you use a singleton is to cover an instance where there must be a single "broker" controlling access to a resource. Singletons are good in loggers because they broker access to, say, a file, which can only be written to exclusively. For something like logging, they provide a way of abstracting away the writes to something like a log file -- you could wrap a caching mechanism to your singleton, etc...

Also think of a situation where you have an application with many windows/threads/etc, but which needs a single point of communication. I once used one to control jobs that I wanted my application to launch. The singleton was responsible for serializing the jobs and displaying their status to any other part of the program which was interested. In this sort of scenario, you can look at a singleton as being sort of like a "server" class running inside your application... HTH

9
votes

I think singleton use can be thought of as the same as the many-to-one relationship in databases. If you have many different parts of your code that need to work with a single instance of an object, that is where it makes sense to use singletons.

6
votes

A practical example of a singleton can be found in Test::Builder, the class which backs just about every modern Perl testing module. The Test::Builder singleton stores and brokers the state and history of the test process (historical test results, counts the number of tests run) as well as things like where the test output is going. These are all necessary to coordinate multiple testing modules, written by different authors, to work together in a single test script.

The history of Test::Builder's singleton is educational. Calling new() always gives you the same object. First, all the data was stored as class variables with nothing in the object itself. This worked until I wanted to test Test::Builder with itself. Then I needed two Test::Builder objects, one setup as a dummy, to capture and test its behavior and output, and one to be the real test object. At that point Test::Builder was refactored into a real object. The singleton object was stored as class data, and new() would always return it. create() was added to make a fresh object and enable testing.

Currently, users are wanting to change some behaviors of Test::Builder in their own module, but leave others alone, while the test history remains in common across all testing modules. What's happening now is the monolithic Test::Builder object is being broken down into smaller pieces (history, output, format...) with a Test::Builder instance collecting them together. Now Test::Builder no longer has to be a singleton. Its components, like history, can be. This pushes the inflexible necessity of a singleton down a level. It gives more flexibility to the user to mix-and-match pieces. The smaller singleton objects can now just store data, with their containing objects deciding how to use it. It even allows a non-Test::Builder class to play along by using the Test::Builder history and output singletons.

Seems to be there's a push and pull between coordination of data and flexibility of behavior which can be mitigated by putting the singleton around just shared data with the smallest amount of behavior as possible to ensure data integrity.

6
votes

When you load a configuration Properties object, either from the database or a file, it helps to have it as a singleton; there's no reason to keep re-reading static data that won't change while the server is running.

4
votes

Shared resources. Especially in PHP, a database class, a template class, and a global variable depot class. All have to be shared by all modules/classes that are being used throughout the code.

It's a true object usage -> the template class contains the page template that is being built, and it gets shaped, added, changed by modules that are adding to page output. It has to be kept as a single instance so that this can happen, and the same goes for databases. With a shared database singleton, all modules' classes can get access to queries and get them without having to rerun them.

A global variable depot singleton provides you a global, reliable, and easily usable variable depot. It tidies up your code a great lot. Imagine having all configuration values in an array in a singleton like:

$gb->config['hostname']

or having all language values in an array like:

$gb->lang['ENTER_USER']

In the end of running the code for the page, you get, say, a now mature:

$template

Singleton, a $gb singleton that has the lang array for replacing into it, and all output loaded and ready. You just replace them into the keys that are now present in mature template object's page value, and then serve it out to user.

The great advantage of this is you can do ANY post-processing you like on anything. You can pipe all language values to google translate, or another translate service and get them back, and replace them into their places, translated, for example. or, you can replace in page structures, or, content strings, as you want.

3
votes

As everyone has said, a shared resource - specifically something that cannot handle concurrent access.

One specific example that I have seen, is a Lucene Search Index Writer.

3
votes

You can use Singleton when implementing the State pattern (in the manner shown in the GoF book). This is because the concrete State classes have no state of their own, and perform their actions in terms of a context class.

You can also make Abstract Factory a singleton.

2
votes

First of all, let's distinguish between Single Object and Singleton. The latter is one of many possible implementations of the former. And the Single Object's problems are different from Singleton's problems. Single Objects are not inherently bad and sometimes are the only way to do things. In short:

  • Single Object - I need just one instance of an object in a program
  • Singleton - create a class with a static field. Add a static method returning this field. Lazily instantiate a field on the first call. Always return the same object.
public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton instance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

As you can see, "Singleton" pattern in its canonical form is not very testing-friendly. This can be easily fixed, though: just make the Singleton implement an interface. Let's call it "Testable Singleton" :)

public class Singleton implements ISingleton {
    private static Singleton instance;

    private Singleton() {}

    public static ISingleton instance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Now we can mock Singleton because we use it via the interface. One of the claims is gone. Let's see if we can get rid of another claim - shared global state.

If we strip Singleton pattern down, at its core it's about lazy initialization:

public static ISingleton instance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
}

That's the whole reason for it to exist. And that's the Single Object pattern. We take it away and put to the factory method, for instance:

public class SingletonFactory {
    private static ISingleton instance;

    // Knock-knock. Single Object here
    public static ISingleton simpleSingleton() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

What's the difference with our Testable Singleton? There is none, because this is the essense of the Single Object pattern - it doesn't matter whether you implement it as a Singleton or a Factory Method or a Service Locator. You still have some shared global state. This can become a problem if it's accessed from multiple threads. You will have to make simpleSingleton() synchronized and cope with all the multithreading issues.

One more time: whatever approach you choose, you will have to pay the Single Object price. Using a Dependency Injection container just shifts the complexity to the framework which will have to cope with Single Object's inherent issues.

Recap:

  1. Most of people who mention Singleton mean Single Object
  2. One of the popular ways to implement it is the Singleton pattern
  3. It has its flaws that can be mitigated
  4. However, the most of Singleton's complexity roots in Single Object's complexity
  5. Regardless of how you instantiate your Single Object, it's still there, be it a Service Locator, a Factory Method or something else
  6. You can shift the complexity to a DI container which is (hopefully) well-tested
  7. Sometimes using the DI container is cumbersome - imagine injecting a LOGGER to every class
1
votes

I use it for an object encapsulating command-line parameters when dealing with pluggable modules. The main program doesn't know what the command-line parameters are for modules that get loaded (and doesn't always even know what modules are being loaded). e.g., main loads A, which doesn't need any parameters itself (so why it should take an extra pointer / reference / whatever, I'm not sure - looks like pollution), then loads modules X, Y, and Z. Two of these, say X and Z, need (or accept) parameters, so they call back to the command-line singleton to tell it what parameters to accept, and the at runtime they call back to find out if the user actually has specified any of them.

In many ways, a singleton for handling CGI parameters would work similarly if you're only using one process per query (other mod_* methods don't do this, so it'd be bad there - thus the argument that says you shouldn't use singletons in the mod_cgi world in case you port to the mod_perl or whatever world).

1
votes

It can be very pragmatic to configure specific infrastructure concerns as singletons or global variables. My favourite example of this is Dependency Injection frameworks that make use of singletons to act as a connection point to the framework.

In this case you are taking a dependency on the infrastructure to simplify using the library and avoid unneeded complexity.

1
votes

I think if your app has multiple layers e.g presentation, domain and model. Singleton is a good candidate to be a part of cross cutting layer. And provide service to each layer in the system.

Essentially Singleton wraps a service for example like logging, analytics and provides it to other layers in the system.

And yes singleton needs to follow single responsibility principle.

0
votes

You use the Singleton design pattern when you want to ensure that a class will have one instance, and that instance will have a global point of access to it.

So let's say that you have an application that requires to a database to process CRUD operations. Ideally you'd use the same connection object to the database to access the database and perform the CRUD operations.

Therefore, in order to ensure that the database class will have one object, and that same object will be used through out the application we implement the singleton design pattern.

Ensure that your constructor is private and that you provide a static method to provide access to the single object of the singleton class

0
votes

So I'm reading up on the singleton pattern for school, and the professors curated a list of current opinions and best practices on the subject. There seems to be agreement on the idea that a singleton is okay to use if you build it such that it doesn't add anything to the code. If you make it so that singleton use can be toggled on and off with literally no side effects other than work load, then it's safe and desirable to use this design pattern.

-1
votes

An example with code, perhaps.

Here, the ConcreteRegistry is a singleton in a poker game that allows the behaviours all the way up the package tree access the few, core interfaces of the game (i.e., the facades for the model, view, controller, environment, etc.):

http://www.edmundkirwan.com/servlet/fractal/cs1/frac-cs40.html

Ed.