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
320
votes
24 answers

Singleton: How should it be used

Edit: From another question I provided an answer that has links to a lot of questions/answers about singletons: More info about singletons here: So I have read the thread Singletons: good design or a crutch? And the argument still rages. I see…
Martin York
  • 257,169
  • 86
  • 333
  • 562
312
votes
2 answers

Why does Apple recommend to use dispatch_once for implementing the singleton pattern under ARC?

What's the exact reason for using dispatch_once in the shared instance accessor of a singleton under ARC? + (MyClass *)sharedInstance { // Static local predicate must be initialized to 0 static MyClass *sharedInstance = nil; static…
Proud Member
  • 40,078
  • 47
  • 146
  • 231
289
votes
5 answers

How to create module-wide variables in Python?

Is there a way to set up a global variable inside of a module? When I tried to do it the most obvious way as appears below, the Python interpreter said the variable __DBNAME__ did not exist. ... __DBNAME__ = None def initDB(name): if not…
daveslab
  • 10,000
  • 21
  • 60
  • 86
265
votes
11 answers

Is the C# static constructor thread safe?

In other words, is this Singleton implementation thread safe: public class Singleton { private static Singleton instance; private Singleton() { } static Singleton() { instance = new Singleton(); } public static…
urini
  • 32,483
  • 14
  • 40
  • 37
224
votes
6 answers

Implementing Singleton with an Enum (in Java)

I have read that it is possible to implement Singleton in Java using an Enum such as: public enum MySingleton { INSTANCE; } But, how does the above work? Specifically, an Object has to be instantiated. Here, how is MySingleton being…
Anand
  • 20,708
  • 48
  • 131
  • 198
223
votes
2 answers

Singleton by Jon Skeet clarification

public sealed class Singleton { Singleton() {} public static Singleton Instance { get { return Nested.instance; } } class Nested { // Explicit static constructor to tell C#…
amutha
  • 2,263
  • 2
  • 14
  • 3
213
votes
22 answers

Creating the Singleton design pattern in PHP5

How would one create a Singleton class using PHP5 classes?
Andrew Moore
  • 93,497
  • 30
  • 163
  • 175
205
votes
25 answers

How to define Singleton in TypeScript

What is the best and most convenient way to implement a Singleton pattern for a class in TypeScript? (Both with and without lazy initialisation).
maja
  • 17,250
  • 17
  • 82
  • 125
200
votes
15 answers

What is a singleton in C#?

What is a Singleton and when should I use it?
Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254
178
votes
10 answers

How do I implement an Objective-C singleton that is compatible with ARC?

How do I convert (or create) a singleton class that compiles and behaves correctly when using automatic reference counting (ARC) in Xcode 4.2?
cescofry
  • 3,706
  • 3
  • 26
  • 22
167
votes
21 answers

Singleton with Arguments in Java

I was reading the Singleton article on Wikipedia and I came across this example: public class Singleton { // Private constructor prevents instantiation from other classes private Singleton() {} /** * SingletonHolder is loaded on…
Scott
146
votes
10 answers

Java serialization: readObject() vs. readResolve()

The book Effective Java and other sources provide a pretty good explanation on how and when to use the readObject() method when working with serializable Java classes. The readResolve() method, on the other hand, remains a bit of a mystery.…
Forage
  • 2,726
  • 2
  • 18
  • 20
142
votes
11 answers

Is there a use-case for singletons with database access in PHP?

I access my MySQL database via PDO. I'm setting up access to the database, and my first attempt was to use the following: The first thing I thought of is global: $db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'root', 'pwd'); function…
seriousdev
  • 7,519
  • 8
  • 45
  • 52
134
votes
8 answers

Java Singleton and Synchronization

Please clarify my queries regarding Singleton and Multithreading: What is the best way to implement Singleton in Java, in a multithreaded environment? What happens when multiple threads try to access getInstance() method at the same time? Can we…
RickDavis
  • 2,276
  • 6
  • 25
  • 31
121
votes
12 answers

What's Alternative to Singleton

We have a class that holds configuration information for the application. It used to be a singleton. After some architectural review, we were told to remove the singleton. We did see some benefits of not using singleton in the unit testing because…
John Mill
  • 1,213
  • 2
  • 9
  • 5