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

Singleton Per Call Context (Web Request) in Unity

A few days ago, I had an issue with ASP.Net threading. I wanted to have a singleton object per web request. I actually need this for my unit of work. I wanted to instantiate a unit of work per web request so that identity map is valid through out…
Mehdi Khalili
  • 927
  • 1
  • 11
  • 18
44
votes
11 answers

Dependency Injection vs Service Location

I am currently weighing up the advantages and disadvantages between DI and SL. However, I have found myself in the following catch 22 which implies that I should just use SL for everything, and only inject an IoC container into each class. DI Catch…
44
votes
4 answers

Using .tupled method when companion object is in class

I am in the process of migrating from Slick to Slick 2, and in Slick 2 you are meant to use the tupled method when projecting onto a case class (as shown here http://slick.typesafe.com/doc/2.0.0-RC1/migration.html) The problem is when the case class…
mdedetrich
  • 1,899
  • 1
  • 18
  • 29
44
votes
3 answers

Get application context from non activity singleton class

In my android project, I have ImageAdapter class in which I pass app context for some further needs. public class ImageAdapter extends BaseAdapter { private Context c; public ImageAdapter(Context c) { this.c = c; } …
Dmitry
  • 670
  • 1
  • 6
  • 11
44
votes
9 answers

Singleton in Cluster environment

What is the best strategy to refactor a Singleton object to a cluster environment? We use Singleton to cache some custom information from Database. Its mostly read-only but gets refreshed when some particular event occurs. Now our application needs…
lud0h
  • 2,370
  • 6
  • 33
  • 41
43
votes
4 answers

When would the garbage collector erase an instance of an object that uses Singleton pattern?

When would the garbage collector erase an instance of an object that uses Singleton pattern? Does an object hang around any longer than a regular object? How can you manually force deletion/garbage collection of an object in Java? Thanks.
Julio
  • 1,815
  • 7
  • 20
  • 22
43
votes
9 answers

How to deal with Singleton along with Serialization

Consider I have a Singleton class defined as follows. public class MySingleton implements Serializable{ private static MySingleton myInstance; private MySingleton(){ } static{ myInstance =new MySingleton(); } public static MySingleton…
frictionlesspulley
  • 11,070
  • 14
  • 66
  • 115
43
votes
11 answers

Java double checked locking

I happened upon an article recently discussing the double checked locking pattern in Java and its pitfalls and now I'm wondering if a variant of that pattern that I've been using for years now is subject to any issues. I've looked at many posts and…
43
votes
2 answers

Getting a reference to the UIApplication delegate

I'm writing my first iPhone application and I'm having trouble switching views. I have 2 views and a reference to each in the AppDelegate (an instance of UIApplicationDelegate). I create instances of both in the applicationDidFinishLaunching and…
derGral
  • 1,836
  • 4
  • 19
  • 29
42
votes
3 answers

Difference between static function and singleton class in swift

I want to create a class where all utility methods will be kept and these methods will be used throughout the app. Problem:1 Is it good to create a singleton class and keep all necessary methods there or should I create a class where all function…
Sunil Sharma
  • 2,653
  • 1
  • 25
  • 36
41
votes
10 answers

Can any one provide me a sample of Singleton in c++?

I write a singleton c++ in the follow way: class A { private: static A* m_pA; A(); virtual ~A(); public: static A* GetInstance(); static void FreeInstance(); void WORK1(); void…
user25749
  • 4,825
  • 14
  • 61
  • 83
41
votes
6 answers

"Singleton" factories, ok or bad?

I've a lot of (abstract) factories and they're usually implemented as singletons. Usually for the convenience of not having to pass them through layers who really have no business with using or knowing these factories. Most of the times I only need…
leeeroy
  • 11,216
  • 17
  • 52
  • 54
40
votes
4 answers

How do I implement convenient logging without a Singleton?

My current implementation, simplified: #include #include class Log { public: ~Log() { // closing file-descriptors, etc... } static void LogMsg( const std::string& msg ) { static std::unique_ptr
kfmfe04
  • 14,936
  • 14
  • 74
  • 140
40
votes
5 answers

Singleton lazy vs eager instantiation

If a singleton is implemented as follows, class Singleton { private static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; } } How is this implementation different from the lazy…
java_geek
  • 17,585
  • 30
  • 91
  • 113
40
votes
6 answers

ASP .NET Singleton

Just want to make sure I am not assuming something foolish here, when implementing the singleton pattern in an ASP .Net web application the static variable scope is only for the current user session, right? If a second user is accessing the site it…
Wesly
  • 679
  • 2
  • 7
  • 11