Questions tagged [singleton]
Singleton is a Gang of Four's creational design pattern that ensures that exactly one application-wide instance of a particular class exists. Use this tag for questions about the singleton design pattern. Do not use this tag for questions that include the singleton design pattern but are not about it.
                                	
	singleton
    
                            
                        
                    
            8,697
            questions
        
        
            2169
            votes
        
        
            36
            answers
        
        
            644k
            views
        
    What are drawbacks or disadvantages of singleton pattern? [closed]
                The singleton pattern is a fully paid up member of the GoF's patterns book, but it lately seems rather orphaned by the developer world. I still use quite a lot of singletons, especially for factory ...
            
        
       
    
            2059
            votes
        
        
            42
            answers
        
        
            661k
            views
        
    Difference between static class and singleton pattern?
                What real (i.e. practical) difference exists between a static class and a singleton pattern?
Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-...
            
        
       
    
            1683
            votes
        
        
            42
            answers
        
        
            714k
            views
        
    What is the best way of implementing singleton in Python
                This question is not for the discussion of whether or not the singleton design pattern is desirable, is an anti-pattern, or for any religious wars, but to discuss how this pattern is best implemented ...
            
        
       
    
            1009
            votes
        
        
            6
            answers
        
        
            192k
            views
        
    class << self idiom in Ruby
                What does class << self do in Ruby?
            
        
       
    
            897
            votes
        
        
            24
            answers
        
        
            972k
            views
        
    How do you implement the Singleton design pattern?
                Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real-life example):
// a lot of methods are omitted ...
            
        
       
    
            852
            votes
        
        
            29
            answers
        
        
            337k
            views
        
    What is an efficient way to implement a singleton pattern in Java? [closed]
                What is an efficient way to implement a singleton design pattern in Java?
            
        
       
    
            608
            votes
        
        
            17
            answers
        
        
            312k
            views
        
    How to declare global variables in Android?
                I am creating an application which requires login. I created the main and the login activity.
In the main activity onCreate method I added the following condition:
public void onCreate(Bundle ...
            
        
       
    
            596
            votes
        
        
            30
            answers
        
        
            139k
            views
        
    Using a dispatch_once singleton model in Swift
                I'm trying to work out an appropriate singleton model for usage in Swift. So far, I've been able to get a non-thread safe model working as:
class var sharedInstance: TPScopeManager {
    get {
       ...
            
        
       
    
            567
            votes
        
        
            24
            answers
        
        
            315k
            views
        
    On design patterns: When should I use the singleton?
                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.
            
        
       
    
            536
            votes
        
        
            21
            answers
        
        
            465k
            views
        
    Is there a simple, elegant way to define singletons? [duplicate]
                There seem to be many ways to define singletons in Python. Is there a consensus opinion on Stack Overflow?
            
        
       
    
            507
            votes
        
        
            31
            answers
        
        
            296k
            views
        
    How do you build a Singleton in Dart?
                The singleton pattern ensures only one instance of a class is ever created. How do I build this in Dart?
            
        
       
    
            469
            votes
        
        
            46
            answers
        
        
            354k
            views
        
    Simplest/cleanest way to implement a singleton in JavaScript
                What is the simplest/cleanest way to implement the singleton pattern in JavaScript?
            
        
       
    
            378
            votes
        
        
            10
            answers
        
        
            143k
            views
        
    Singletons vs. Application Context in Android?
                Recalling this post enumerating several problems of using singletons
and having seen several examples of Android applications using singleton pattern, I wonder if it's a good idea to use Singletons ...
            
        
       
    
            348
            votes
        
        
            10
            answers
        
        
            99k
            views
        
    Create singleton using GCD's dispatch_once in Objective-C
                If you can target iOS 4.0 or above
Using GCD, is it the best way to create singleton in Objective-C (thread safe)?
+ (instancetype)sharedInstance
{
    static dispatch_once_t once;
    static id ...
            
        
       
    
            333
            votes
        
        
            26
            answers
        
        
            185k
            views
        
    What should my Objective-C singleton look like? [closed]
                My singleton accessor method is usually some variant of:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
    @synchronized(self)
    {
        if (gInstance == NULL)
            gInstance =...
            
        
       
    
            321
            votes
        
        
            24
            answers
        
        
            215k
            views
        
    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 ...
            
        
       
    
            313
            votes
        
        
            2
            answers
        
        
            80k
            views
        
    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
    ...
            
        
       
    
            292
            votes
        
        
            5
            answers
        
        
            381k
            views
        
    How to create module-wide variables in Python? [duplicate]
                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.
...
...
            
        
       
    
            265
            votes
        
        
            11
            answers
        
        
            70k
            views
        
    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()
    {
        ...
            
        
       
    
            225
            votes
        
        
            6
            answers
        
        
            157k
            views
        
    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 ...
            
        
       
    
            223
            votes
        
        
            2
            answers
        
        
            48k
            views
        
    Singleton by Jon Skeet clarification
                public sealed class Singleton
{
    Singleton() {}
    public static Singleton Instance
    {
        get
        {
            return Nested.instance;
        }
    }
    class Nested
    {
        ...
            
        
       
    
            217
            votes
        
        
            26
            answers
        
        
            210k
            views
        
    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).
            
        
       
    
            213
            votes
        
        
            22
            answers
        
        
            204k
            views
        
    Creating the Singleton design pattern in PHP5
                How would one create a Singleton class using PHP5 classes?
            
        
       
    
            201
            votes
        
        
            15
            answers
        
        
            207k
            views
        
    What is a singleton in C#?
                What is a Singleton and when should I use it?
            
        
       
    
            178
            votes
        
        
            10
            answers
        
        
            98k
            views
        
    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?
            
        
       
    
            169
            votes
        
        
            21
            answers
        
        
            164k
            views
        
    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() {...
            
        
       
    
            147
            votes
        
        
            10
            answers
        
        
            106k
            views
        
    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 ...
            
        
       
    
            142
            votes
        
        
            11
            answers
        
        
            44k
            views
        
    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;...
            
        
       
    
            135
            votes
        
        
            8
            answers
        
        
            134k
            views
        
    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 ...
            
        
       
    
            123
            votes
        
        
            12
            answers
        
        
            56k
            views
        
    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 ...
            
        
       
    
            115
            votes
        
        
            8
            answers
        
        
            53k
            views
        
    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 ...
            
        
       
    
            112
            votes
        
        
            10
            answers
        
        
            118k
            views
        
    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 ...
            
        
       
    
            112
            votes
        
        
            11
            answers
        
        
            142k
            views
        
    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 ...
            
        
       
    
            110
            votes
        
        
            11
            answers
        
        
            175k
            views
        
    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;
...
            
        
       
    
            103
            votes
        
        
            7
            answers
        
        
            59k
            views
        
    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<X> as a default. That is, I ...
            
        
       
    
            103
            votes
        
        
            5
            answers
        
        
            87k
            views
        
    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<IFoo, Foo>();
And let's say the Foo class has a number of other dependencies (mostly ...
            
        
       
    
            99
            votes
        
        
            8
            answers
        
        
            33k
            views
        
    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;
    ...
            
        
       
    
            98
            votes
        
        
            3
            answers
        
        
            145k
            views
        
    Javascript: best Singleton pattern [duplicate]
                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 () {
...
            
        
       
    
            96
            votes
        
        
            13
            answers
        
        
            39k
            views
        
    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 ...
            
        
       
    
            94
            votes
        
        
            16
            answers
        
        
            25k
            views
        
    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 ...
            
        
       
    
            94
            votes
        
        
            8
            answers
        
        
            28k
            views
        
    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 ...
            
        
       
    
            93
            votes
        
        
            5
            answers
        
        
            47k
            views
        
    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 ...
            
        
       
    
            93
            votes
        
        
            6
            answers
        
        
            38k
            views
        
    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 ...
            
        
       
    
            92
            votes
        
        
            0
            answers
        
        
            125k
            views
        
    Python and the Singleton Pattern [duplicate]
                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...
            
        
       
    
            91
            votes
        
        
            8
            answers
        
        
            55k
            views
        
    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 ...
            
        
       
    
            89
            votes
        
        
            4
            answers
        
        
            84k
            views
        
    Singleton with properties in Swift 3
                In Apple's Using Swift with Cocoa and Objective-C document (updated for Swift 3) they give the following example of the Singleton pattern:
class Singleton {
    static let sharedInstance: Singleton = ...
            
        
       
    
            89
            votes
        
        
            8
            answers
        
        
            52k
            views
        
    Is it a good practice to have logger as a singleton?
                I had a habit to pass logger to constructor, like:
public class OrderService : IOrderService {
     public OrderService(ILogger logger) {
     }
}
But that is quite annoying, so I've used it a ...
            
        
       
    
            88
            votes
        
        
            4
            answers
        
        
            78k
            views
        
    What is the best approach for using an Enum as a singleton in Java?
                Building on what has been written in SO question Best Singleton Implementation In Java - namely about using an enum to create a singleton - what are the differences/pros/cons between (constructor ...
            
        
       
    
            87
            votes
        
        
            9
            answers
        
        
            104k
            views
        
    How do you implement a singleton efficiently and thread-safely? [duplicate]
                The usual pattern for a singleton class is something like
static Foo &getInst()
{
  static Foo *inst = NULL;
  if(inst == NULL)
    inst = new Foo(...);
  return *inst;    
}
However, it's my ...
            
        
       
    
            82
            votes
        
        
            2
            answers
        
        
            52k
            views
        
    Using Singleton design pattern for SQLiteDatabase
                I'm rather newbie on Android, and I'm working on a simple application to get some basic experience. My app is pretty simple and consists among other things of a broadcast receiver and some activities. ...