567

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.

6
  • 4
    Since learning erlang, i prefer that approach, namely immutability and message passing.
    – Setori
    Nov 26, 2009 at 4:51
  • 234
    What isn't constructive about this question? I see constructive answering below.
    – mk12
    Jun 25, 2013 at 23:04
  • 3
    A dependency injection framework is a very complex singleton that gives out object…. Feb 10, 2014 at 19:25
  • 1
    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. Dec 7, 2015 at 15:53
  • 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.
    Feb 1, 2019 at 19:14

24 Answers 24

411

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.

14
  • 3
    @ArneMertz I guess this is the one.
    – Attacktive
    Dec 21, 2013 at 6:40
  • 3
    Why can't you just use a global object? Why does it have to be a singleton?
    – Shoe
    Dec 8, 2015 at 11:07
  • 1
    I think static method for a logging util?
    – Junaid
    Jan 22, 2016 at 5:05
  • 3
    Singletons are best when you need to manage resources. For example, Http connections. You don't want to establish 1 million http clients to a single client, that is crazy wasteful and slow. So a singleton with a connection pooled http client will be much faster and resource friendly.
    – Cogman
    Jun 9, 2016 at 23:53
  • 17
    I know this is a old question, and the information in this answer is great. However, I'm having trouble understanding why this is the accepted answer when the OP clearly specified: "Give me scenarios, other than the good old logger where it makes sense to use the singleton." Jan 4, 2017 at 3:33
152

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.

4
  • 3
    I disagree with point 2. Point 3 is not really a reason (just because you can it doesnt mean you should) and 1 is a good point but i still dont see use to it. Lets say the shared resource is a disk drive or a db cache. You can add another drive or have a db cache focusing on another thing (such as a cache for a specialized table for one thread with the other being more general purpose).
    – user34537
    Jul 1, 2011 at 2:53
  • 21
    I think you missed the word "candidate". A Singleton candidate must satisfy the three requirements; just because something meets the requirements, doesn't mean it should be a Singleton. There may be other design factors :)
    – metao
    Jul 4, 2011 at 3:16
  • A print spooler does not meet the criteria. You may want a test print spooler that doesn't actually print, for testing.
    – user253751
    Jul 1, 2020 at 15:09
  • Say if you have world data expressed with an immutable tree structure, and you want to coordinate the changes to manage concurrency. Would the tree be a candidate for singleton?
    – DavidY
    Dec 30, 2021 at 1:01
62

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

6
  • 8
    Similar to Properties.Settings.Default in .NET. Dec 5, 2011 at 2:21
  • 11
    @Paul, The "no-singleton camp" will state that the configuration object should simply be passed into functions that need it, instead of making it globally accessible (aka singleton).
    – Pacerier
    Jun 25, 2014 at 1:49
  • 2
    Disagree. Should the configuration be moved to the database, everything's screwed. Should the path to the configuration depend on anything outside that singleton, these things need to be static too.
    – rr-
    Aug 28, 2015 at 21:01
  • 3
    @PaulCroarkin Can you expand on this and explain how this is beneficial?
    – Alex
    Apr 19, 2017 at 23:55
  • 2
    @rr- if the configuration moves to the database, it can still be encapsulated in a configuration object which will be passed into functions that need it. (P.S. I'm not in the "no-singleton" camp). Apr 6, 2020 at 15:56
51

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.

8
  • 41
    I've heard this printer spooler example and I think it's kind of lame. Who says I can't have more than one spooler? What the heck is a printer spooler anyway? What if I have different kinds of printers that can't conflict or use different drivers? Oct 23, 2008 at 3:01
  • 8
    Its just an example...for any situation that anyone use as an example you will be able to find an alternative design that makes the example useless. Lets pretend that the spooler manages a single resource that is shared by multiple components. It works. Oct 23, 2008 at 14:54
  • 4
    It's the classic example for the Gang of Four. I think an answer with a real tried out use case would be more useful. I mean a situation where you actually felt the Singleton is the best solution. Sep 16, 2009 at 17:15
  • 2
    What the heck is a printer spooler? May 16, 2018 at 21:05
  • 1
    @1800INFORMATION so, after all these years, what is a printer spooler?..
    – Sajuuk
    May 27, 2019 at 11:41
28

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

8
  • 6
    User language can only be singleton with the assumption that only one user can use the system. Apr 10, 2014 at 14:43
  • 3
    …and that one user only speaks one language.
    – spectras
    Jan 23, 2020 at 15:42
  • 4
    @SamuelÅslund If it's a desktop application that is a fair assumption
    – user253751
    Jul 1, 2020 at 15:10
  • 1
    @user253751 Yes it is, until it suddenly is not any more, it took a lot of work to transform Javas Language singleton into something that could support internationalized websites. I have found that using the singleton as a parameter is often a reasonable compromise, by retrieving the singleton instance in the caller the function using it can be tested in isolation and reused without too much trouble and the obviously global setting do not need to be passed around in long call-stacks. Many languages support default parameters that could be used to avoid duppplication. Jul 5, 2020 at 13:02
  • @spectras though I agree, that is actually a common case for e.g. OS where the last thing you want are mixed languages all over the screen, even if the user'd spoke more.
    – jave.web
    Feb 22, 2021 at 1:07
24

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.

6
  • 3
    Wouldn't a database connection generator be an example of a Factory?
    – Ken
    Nov 2, 2010 at 20:58
  • 4
    @Ken you would want that factory to be a singleton in almost all cases. May 23, 2011 at 20:09
  • 3
    @Federico, The "no-singleton camp" will state that these database connection(s) should simply be passed into functions that need them, instead of making them globally accessible (aka singleton).
    – Pacerier
    Jun 25, 2014 at 1:51
  • 3
    You don't really need a singleton for this. It can be injected. Feb 10, 2017 at 1:23
  • @NestorLedon it really comes down to how often are you using it, it can be done both ways, but if you'd use something in the 99% of the application, dependency injection may not be the way. On the other hand if you use it only sometimes, but still it should be the "same" "thing", then dep.inj. could be the way :)
    – jave.web
    Feb 22, 2021 at 1:23
16

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.

13

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

1
  • 4
    Loggers are most often Singletons so that logging objects do not have to be passed around. Any decent implementation of a log stream will ensure that concurrent writes are impossible, whether it is a Singleton or not.
    – metao
    Oct 23, 2008 at 1:35
12

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.

8

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.

5
  • 5
    Why would you not just load the data once and pass the configuration object as needed?
    – lagweezle
    Sep 28, 2016 at 23:05
  • 1
    what is with the passing around??? If I had to pass around every object I need I would have constructors with 20 arguments...
    – Enerccio
    Apr 18, 2018 at 17:12
  • @Enerccio If you have objects that rely on 20 different others with no encapsulation, you already have major design issues.
    – spectras
    Jan 23, 2020 at 15:45
  • @spectras Do I? If I implement gui dialog I will need: repository, localization, session data, application data, widget parent, client data, permission manager and probably more. Sure, you can aggregate some, but why? Personally I use spring and aspects to just autowire all these dependencies into the widget class and that decouples everything.
    – Enerccio
    Jan 25, 2020 at 23:24
  • If you have that much state, you could consider implementing a facade, giving a view of relevant aspects to the specific context. Why? Because it would allow a clean design without either of the singleton or 29-arg constructor antipatterns. Actually the very fact your gui dialog accesses all those things yells "violation of the single responsibility principle".
    – spectras
    Jan 26, 2020 at 12:03
7

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.

5

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.

1
  • 21
    You might want to break your answer into multiple paragraphs and block out the code segments for readability.
    – Justin
    Nov 2, 2010 at 20:44
5

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
5

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

4

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.

5
  • This is the case I am dealing with now in a project. I used a state pattern to remove repetitive conditional code from the context's methods. The state's have no instance variables of their own. However, I am on the fence in regard to whether I should make them singletons. Everytime the state switches a new instance is instantiated. This does seem wasteful because there is no way the instance can be any different from another one, (because there are no instance variables). I am trying to figure out why I shouldn't use it. Mar 23, 2017 at 19:07
  • 1
    @kiwicomb123 Try to make your setState() responsible for deciding the state creation policy. It helps if your programming language supports templates or generics. Instead of Singleton, you could use the Monostate pattern, where instantiating a state object ends up reusing the same global/static state object. The syntax for changing the state could remain unchanged, as your users need not be aware that the instantiated state is a Monostate. Mar 23, 2017 at 20:27
  • Okay so in my states I could just make all the methods static, so whenever a new instance is created it doesn't have the same overhead? I am a bit confused, I need to read-up about the Monostate pattern. Mar 25, 2017 at 21:53
  • @kiwicomb123 No, Monostate is not about making all members static. Better that you read up on it, then check SO for related questions and answers. Mar 26, 2017 at 23:56
  • I feel this should have more votes. Abstract factory is common enough and since factories are stateless, stable in being stateless, and can't be implemented with static methods (in Java) which are not overriden, use of singleton should be okay.
    – DPM
    Aug 27, 2019 at 13:51
3

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.

0
2

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.

1

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

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.

0

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.

0

Singleton pattern is the most pervasive pattern in the Spring containerization approach. If we look at that in terms of architectural primitives - they form a blackboard graph of objects, to which every thread can read and write. They do the dramatic act of synchronizing between multiple threads. The very reason why multiple threads need to synchronize is because there are always resources that underlie a computational program, over which contention might occur. Consider what is called a 'last seat problem'. A flight is being booked, but there are multiple ways to do it. For simplicity lets assume that the data about the flight occupancy is stored in a flat file rather than a database. Now, if there are two threads, each functionally different (i.e represented by different endpoints in the webapp) and let one of these threads A, be the thread which a prospective passenger uses to make a booking and the other one B is which a flight manager uses to close the booking - virtually closing the boarding door. Then, if these threads do not use singleton, the flight object would be detached from the real resource out-there, which we say not the actual aeroplane but the entry in the flat file. The A thread would have reference to an object, while the passenger is still fighting a dilemma whether to fly or not and then finally when he makes up his mind, the B thread would already have closed the door. But the object referenced by the A thread would still show one more seat to go. Now, cutting out the RDBMS due to our initial assumption, the system would write a ticket for the passenger and issue it to him eventhough the boarding is closed. Now, in a singleton implementation, the moment the theread B accesses the system, the universal object Flight is updated with status closed. Hence, if the passenger finally makes up his mind and clicks confirm, he would get an error right away. All this would not have been possible without the singleton. Hence, singleton allows you to stay close to the resources and avoids thread contention.

1
  • If we observe closely, the use of singleton pattern reduces the possibility for factory pattern. In spring specifically, there could not be any runtime polymorophism worth mentioning implemented
    – premganz
    Oct 29, 2021 at 9:43
0

I don't think the scenarios for Singleton are related to a logger neither a printer pool or whatever the example would be.

Singleton decision will be make with the purpose to optimize hardware resources instead of having only one place to control any logger or printer pool

I personally think that singleton is used when:

  1. The object that we are talking about it is instantiated always in the same way (i.e. any shared resource like Logger or printer pool)

  2. It is called multiple times (This can be 100 or 1000 and it is related to your resources)

  3. Your hardware resources are limited (i.e. memory, processing power, etc).

If you have a huge amount of memory space and processing power I don't see a need to use singleton.

Singleton will make sure that you will only have one instance and is lazy loaded then if it is called one million times you are creating only one object.

-1

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.

1
  • 2
    Link is now broken, but if you're registering view information in a singleton, which will be accessed throughout the application, you're missing the point of MVC. A view is updated by (and communicates to) a controller, which uses the model. As it sounds here, it's probably a misuse of Singleton and a refactoring is in order.
    – drharris
    May 27, 2010 at 21:38
-1

The primary purpose of Singleton class is to restrict the number of instances created and hence ensure access control to resources.

The memory space wastage does not occur with the use of the singleton class because it restricts the instance creation. As the object creation will take place only once instead of creating it each time a new request is made.

Singleton class uses mutex inside and hence making it thread-safe. This is the reason why the multi-threaded and database applications mostly make use of the Singleton pattern in Java for caching, logging, thread pooling, configuration settings, and much more

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.