Questions tagged [singleton]

A design pattern that ensures that exactly one application-wide instance of a particular class exists. One of the Gang of Four's creational design patterns.

Singleton is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

public class SingletonDemo {
    private static volatile SingletonDemo instance = null;

    private SingletonDemo() {
    }

    public static SingletonDemo getInstance() {
        if (instance == null) {
            synchronized (SingletonDemo.class){
                if (instance == null) {
                    instance = new SingletonDemo ();
                }
            }
        }
        return instance;
    }
}

Implementations of Singleton may include additional features such as thread-safe initialization, or some form of initialization order.

Singleton is arguably the most well-known, the most used, the most abused, and the most disputed design pattern in existence, frequently leading to heated discussions between its proponents and opponents.

This is one of the Gang of Four's creational , first published in Gamma et al.'s book "Design Patterns: Elements of Reusable Object-Oriented Software".

More information is available on Wikipedia.

8550 questions
113
votes
8 answers

Why use a singleton instead of static methods?

I have never found good answers to these simple questions about helper/utility classes: Why would I create a singleton (stateless) instead of using static methods? Why would an object instance be needed if an object has no state?
Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419
112
votes
11 answers

Singleton design pattern vs Singleton beans in Spring container

As we all know we have beans as singleton by default in Spring container and if we have a web application based on Spring framework then in that case do we really need to implement Singleton design pattern to hold global data rather than just…
Peeyush
  • 1,121
  • 2
  • 8
  • 3
112
votes
10 answers

Singleton pattern in nodejs - is it needed?

I recently came across this article on how to write a singleton in Node.js. I know the documentation of require states that: Modules are cached after the first time they are loaded. Multiple calls to require('foo') may not cause the module code to…
mkoryak
  • 57,086
  • 61
  • 201
  • 257
109
votes
11 answers

Thread Safe C# Singleton Pattern

I have some questions regarding the the singleton pattern as documented here: http://msdn.microsoft.com/en-us/library/ff650316.aspx The following code is an extract from the article: using System; public sealed class Singleton { private static…
Wayne Phipps
  • 2,019
  • 6
  • 26
  • 31
100
votes
7 answers

Is there an "Empty List" singleton in C#?

In C# I use LINQ and IEnumerable a good bit. And all is well-and-good (or at least mostly so). However, in many cases I find myself that I need an empty IEnumerable as a default. That is, I would like for (var x in xs) { ... } to work without…
user166390
99
votes
5 answers

ASP.NET Core initialize singleton after configuring DI

So let's say I have a singleton class instance that I register in the DI like this: services.AddSingleton(); And let's say the Foo class has a number of other dependencies (mostly repository classes that allow it to load data). With my…
pbz
  • 8,865
  • 14
  • 56
  • 70
98
votes
3 answers

Javascript: best Singleton pattern

Possible Duplicate: Simplest/Cleanest way to implement singleton in JavaScript? I'm using this pattern for singletons, in the example the singleton is PlanetEarth: var NAMESPACE = function () { var privateFunction1 = function () { …
Kaze no Koe
  • 3,254
  • 1
  • 21
  • 22
95
votes
8 answers

Why is volatile used in double checked locking

From Head First design patterns book, the singleton pattern with double checked locking has been implemented as below: public class Singleton { private volatile static Singleton instance; private Singleton() {} public static Singleton…
toc777
  • 2,607
  • 2
  • 26
  • 37
94
votes
12 answers

SQL Server: how to constrain a table to contain a single row?

I want to store a single row in a configuration table for my application. I would like to enforce that this table can contain only one row. What is the simplest way to enforce the single row constraint ?
Martin
  • 9,674
  • 5
  • 36
  • 36
94
votes
16 answers

Are there any viable alternatives to the GOF Singleton Pattern?

Let's face it. The Singleton Pattern is highly controversial topic with hordes programmers on both sides of the fence. There are those who feel like the Singleton is nothing more then a glorified global variable, and others who swear by pattern…
CodingWithoutComments
  • 35,598
  • 21
  • 73
  • 86
93
votes
5 answers

What exactly is the singleton class in ruby?

Is the singleton class in Ruby a class in and of itself? Is it the reason why all objects belong to "class?" The concept is fuzzy, but I believe it has something to do with why I can define a class method at all (class foo; def foo.bar ...). What is…
keyofnight
  • 1,646
  • 1
  • 13
  • 15
92
votes
0 answers

Python and the Singleton Pattern

What is the best way to implement the singleton pattern in Python? It seems impossible to declare the constructor private or protected as is normally done with the Singleton pattern...
dmanxiii
  • 51,473
  • 10
  • 33
  • 23
91
votes
8 answers

The need for volatile modifier in double checked locking in .NET

Multiple texts say that when implementing double-checked locking in .NET the field you are locking on should have volatile modifier applied. But why exactly? Considering the following example: public sealed class Singleton { private static…
Konstantin
  • 3,817
  • 4
  • 29
  • 39
91
votes
6 answers

Why is the Borg pattern better than the Singleton pattern in Python

Why is the Borg pattern better than the Singleton pattern? I ask because I don't see them resulting in anything different. Borg: class Borg: __shared_state = {} # init internal state variables here __register = {} def __init__(self): …
u0b34a0f6ae
  • 48,117
  • 14
  • 92
  • 101
90
votes
8 answers

Non-Singleton Services in AngularJS

AngularJS clearly states in its documentation that Services are Singletons: AngularJS services are singletons Counterintuitively, module.factory also returns a Singleton instance. Given that there are plenty of use-cases for non-singleton services,…
Undistraction
  • 42,754
  • 56
  • 195
  • 331