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
3
votes
2 answers

Is it required to to use weak reference's within a singleton class?

I came across a tutorial from raywenderlich were the author gave some good tips on handling threading issues in singleton. But when using closures from within the singleton class he is using 'weak' reference cycle. Is it really required so since the…
3
votes
1 answer

How do you deal with CA2000 (Dispose of IDisposable Objects) when the objects are placed in a Dependency Injection container?

According to Microsoft, the best practice for an HttpClient is to maintain a singleton version of an HttpClient (paraphrasing, but that's the upshot. Don't dispose of it immediately). My own testing has show that there are definite advantages to a…
Quark Soup
  • 4,272
  • 3
  • 42
  • 74
3
votes
1 answer

Should immutable global objects be declared as 'const my_result_t BLAH;' or 'extern const my_result_t BLAH;'?

First, some motivating background info; I'm experimenting with the idea of representing error-codes (returned from functions) as super-lightweight human-readable-strings rather than enum-integers, something like this: #include /**…
Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
3
votes
1 answer

Making volatile Executor class in multi-threaded environment

In my spring based application we are initializing threadPool using ExecutorService for concurrent task execution.We don't want the threadPool to be initialised multiple times in case of multithreaded environment, for which we are making our factory…
Ankit
  • 81
  • 2
  • 10
3
votes
1 answer

How implement a LiveData Singleton

I need to pass a Bitmap between activities without write the image in the internal/external memory. An Intent can't carry that size so the best option that I found is to use a Singleton Bitmap or extend Livedata and use it as singleton. (I'm not…
3
votes
3 answers

The best singleton pattern since Java 5

Since Java 5 it is said that the best way to create a singleton is by a single-element enum type. Example: public enum SuperSingleton implements Zooma{ INSTANCE; /** */ public void fightTheBattle(){ System.out.println("I am…
Koekiebox
  • 5,793
  • 14
  • 53
  • 88
3
votes
4 answers

Singleton Vs static variable

I need to use a global counter in my application which increments count for every request made. I am going to put this counter in a separate class something like this: public class Counter{ private static int count = 0; public…
Pan
  • 6,455
  • 5
  • 27
  • 27
3
votes
1 answer

Is Singleton object returned through shared_ptr thread-safe?

I was reading the answers to the question. C++ Singleton design pattern One of the answer suggested to use shared_ptr to guarantee the lifetime when multiple static objects access the singleton object. I noticed that shared_ptr here is constructed…
Sunshyn
  • 43
  • 5
3
votes
1 answer

What to do when you know that only a single instance of a class will ever be instantiated - singleton, static, or plain old class?

There are cases when there is a class which has no inherent reason to be a singleton or static, yet it also doesn't make much sense in creating more than 1 instance of it. The example I'm facing is a "header" object in a PHP page. It's a homebrew…
Vilx-
  • 104,512
  • 87
  • 279
  • 422
3
votes
0 answers

Use of volatile without synchronized for lazy singleton in Android Studio project template "Login Activity"

I am learning Android and have been looking through the base project templates provided by Android Studio 3.4.1. The one called "Login Activity" (accessible via New Project...) sets up an implementation with a Repository class in…
xenull
  • 83
  • 1
  • 6
3
votes
3 answers

How to know if an instance of class came from a Singleton?

I have to evaluate if an instance of a class came from a Singleton or no? I know that in JavaScript to create a Singleton I need to save in the constructor a variable instance (the name could be whatever) that save this. class Singleton { …
3
votes
3 answers

Class vs Instance Scope in JavaScript

I am evaluating a way of use the Singleton Pattern called Monostate in JavaScript. I have some code like the following: class Boss { get name() { return Boss._name } set name(value) { Boss._name = value; } get age() { return Boss._age…
Ruben Saucedo
  • 239
  • 1
  • 13
3
votes
4 answers

How to avoid the performance overhead of using volatile in singleton pattern?

Say Code for Singleton pattern: class Singleton { private volatile static Singleton obj; private Singleton() {} public static Singleton getInstance() { if (obj == null) { synchronized…
csr
  • 31
  • 1
3
votes
2 answers

Can singleton object extend a trait?

I want to extend a trait from Scala object and override those methods which are in trait. So my doubt is those methods will become static to that Object or instance methods, and is this good approach to extend from trait to Scala Object. Please help…
Dev
  • 47
  • 9
3
votes
1 answer

How to use toSing from singletons library?

I'm a newbie when it comes to the singleton library, and may have bitten off more than I can chew here. I've managed to use fromSing successfully to convert a "singleton type" to a "value-level term" (is my terminology correct?) However, I'm unable…
Saurabh Nanda
  • 6,373
  • 5
  • 31
  • 60