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
89
votes
4 answers

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 = { let instance = Singleton() //…
RobertJoseph
  • 7,968
  • 12
  • 68
  • 113
88
votes
8 answers

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 property this for some time: private ILogger logger =…
Giedrius
  • 8,430
  • 6
  • 50
  • 91
88
votes
4 answers

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 omitted) public enum Elvis { INSTANCE; …
Miles D
  • 7,960
  • 5
  • 34
  • 35
86
votes
9 answers

efficient thread-safe singleton in C++

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 understanding that this solution is not thread-safe,…
user168715
  • 5,469
  • 1
  • 31
  • 42
81
votes
2 answers

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. Both components make use of a single database,…
Dan
  • 1,516
  • 2
  • 16
  • 26
81
votes
9 answers

Global or Singleton for database connection?

What is the benefit of using singleton instead of global for database connections in PHP? I feel using singleton instead of global makes the code unnecessarily complex. Code with Global $conn = new PDO(...); function getSomething() { global…
Imran
  • 87,203
  • 23
  • 98
  • 131
78
votes
10 answers

@staticmethod with @property

I want Stats.singleton.twitter_count += 1 and I thought I could do class Stats: singleton_object = None @property @staticmethod def singleton(): if Stats.singleton_object: return Stats.singleton_object …
Paul Tarjan
  • 48,968
  • 59
  • 172
  • 213
78
votes
8 answers

Singleton in Android

I have followed this link and successfully made singleton class in Android. http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/ Problem is that i want a single object. like i have Activity A and…
user2216292
  • 799
  • 1
  • 5
  • 6
75
votes
4 answers

Double Checked Locking in Singleton

here is my custom class for singleton pattern. in this code, I use double-checked locking as below. As I read many posts on some source, they say that double check is useful because it prevents two concurrent threads run at same times make two…
hqt
  • 29,632
  • 51
  • 171
  • 250
72
votes
8 answers

Thread Safe singleton class

I wrote a below Singleton class. I am not sure whether this is thread safe singleton class or not? public class CassandraAstyanaxConnection { private static CassandraAstyanaxConnection _instance; private AstyanaxContext context; …
arsenal
  • 23,366
  • 85
  • 225
  • 331
72
votes
6 answers

How to implement multithread safe singleton in C++11 without using

Now that C++11 has multithreading I was wondering what is the correct way to implement lazy initialized singleton without using mutexes(for perf reasons). I came up with this, but tbh Im not really good at writing lockfree code, so Im looking for…
NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
71
votes
9 answers

Android: Cannot perform this operation because the connection pool has been closed

I was reading through StackOverflow about this question and I still haven't found a solution. I notice that sometimes, my app throws this error: java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been…
Ferran Negre
  • 3,712
  • 3
  • 34
  • 56
69
votes
6 answers

Execute a method when a variable value changes in Swift

I need to execute a function when a variable value changes. I have a singleton class containing a shared variable called labelChange. Values of this variable are taken from another class called Model. I have two VC classes, one of them has a button…
Ilir V. Gruda
  • 1,562
  • 5
  • 17
  • 23
69
votes
8 answers

C++ singleton vs. global static object

A friend of mine today asked me why should he prefer use of singleton over global static object? The way I started it to explain was that the singleton can have state vs. static global object won't...but then I wasn't sure..because this in C++.. (I…
Tom
69
votes
23 answers

Singletons: good design or a crutch?

Singletons are a hotly debated design pattern, so I am interested in what the Stack Overflow community thought about them. Please provide reasons for your opinions, not just "Singletons are for lazy programmers!" Here is a fairly good article on the…
Adam
  • 25,966
  • 23
  • 76
  • 87