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
1 answer

Recommended code style: case object Foo or object Foo extends Serializable?

If I want a serialization-safe singleton, should I prefer case object Foo or object Foo extends Serializable ?
soc
  • 27,983
  • 20
  • 111
  • 215
3
votes
1 answer

Instantiating IHubContext in ASP.NET Core

I am using SignalR on different places of my web project. In my Controllers and HostedService this seems to be working fine. Clients instantiate connections with my hub and I can communicate with them back using an IHubContext instance, injected in…
mh133
  • 135
  • 12
3
votes
2 answers

Copy/Inheritance of Ruby Matrix class (core/std lib)

I tried to extend an existing Singleton class in Ruby, as an example the Matrix class. My first quick&dirty solution was a monkey patch (reopen class and extend with functionality). But I think, monkey patching in general isn't good, especially if…
asaaki
  • 1,970
  • 18
  • 22
3
votes
2 answers

C++ Meyer's Singleton with arguments

Is it possible to define a Meyer's singleton (like this one) with arguments? I know it is possible with the GOF style singleton (like here), but I can't seem to make it work with Meyer's singletons: // ... public: static S& getInstance() { …
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
3
votes
1 answer

InvalidOperationException: Cannot consume scoped service 'Microsoft.JSInterop.IJSRuntime' from singleton '...IAuthentication' in Blazor

I'm creating Blazor project that at first everything works fine until I need to inject IJSRuntime into cs file. Microsoft.JSInterop; ... ... public BaseService(IJSRuntime jSRuntime) { } BaseService is inherited in another service named…
user3856437
  • 2,071
  • 4
  • 22
  • 27
3
votes
1 answer

Singleton NSWindowController won't reopen window after close

I have a singleton NSWindowController (ProjectInfoHUDController) that won't reopen after it has been closed. The object is persisting in memory which I know because any calls made to [ProjectInfoHUDController sharedInstance] both before and after…
Sean
  • 5,810
  • 2
  • 33
  • 41
3
votes
3 answers

Proper way to create a singleton service in ASP.NET Core - does it have to use the static keyword, or not?

This is really confusing for me. Nothing is stopping us from creating a class with instance fields and instance methods, versus creating a class with static fields and static methods. Both can be registered as a singleton. Is there a preferred…
SpiritBob
  • 2,355
  • 3
  • 24
  • 62
3
votes
1 answer

Typescript Class - Should a private field be in the constructor?

I've written a singleton class in Typescript to avoid having the keep declaring/creating the same OktaAuth object namely: new OktaAuth({ issuer: appConfig.OKTA_ORG_URL }). (By the way I did this as I assume this the best way to write such things) So…
userMod2
  • 8,312
  • 13
  • 63
  • 115
3
votes
2 answers

Static reference to instance in IE Toolbar

I am having an interesting issue with a COM component written to function as a toolbar in IE. Basically if you open up several tabs at once in IE the individual instances of the COM objects get all twisted around. Bear with me here. Say I open up…
Mark Williams
  • 583
  • 7
  • 18
3
votes
1 answer

Prism, Unity and default type registration in Modules

Technologies C# 4.0 Prism 4 with Unity for DI WPF MVVM Preface There are two projects in my solution, MyApp.Shell and MyApp.ModuleFoo MyApp.Shell's Unity Bootstrapper protected override IModuleCatalog CreateModuleCatalog() { // Module…
Nick Carlson
  • 243
  • 1
  • 5
  • 13
3
votes
1 answer

Single HttpClient for application life cycle - How does this single instance of HttpClient ensures that it has responded to correct request?

I have created a single instance of HttpClient in Application_Start event to be reused accross the application in Global.asax.cs Code in App start: protected new void Application_Start() { HttpClientHandler httpClientHandler = new…
Sana.91
  • 1,999
  • 4
  • 33
  • 52
3
votes
1 answer

Saving an object into an Entity without persisting it in JPA

I am doing an application in play framework in which I need to store the same instance of a non-Entity object into a JPA Entity without persisting it into the database, I want to know if it's possible to achieve that or not using annotations. A…
dlock
  • 9,447
  • 9
  • 47
  • 67
3
votes
3 answers

I am looking for a lazy, thread-safe implementation to cache the first non-null result of an expensive calculation

I am very new to using singleton and have a hard time understanding the lazy implementation of singleton in C#. Assume I have a string which is initially null/empty and when someone does a get call on that string, I have to calculate the string only…
starkk92
  • 5,754
  • 9
  • 43
  • 59
3
votes
4 answers

Why does the destructor call itself endlessly (causing a stack overflow)?

I am confused on why the destructor calls itself an endless amount of times, when I try to construct an object say LeakySingleton on the heap through a static function call create_instance() and then try to delete it explicitly afterwards via the…
3
votes
1 answer

Singleton object lifetime is process or appdomain?

Recently I have been asked a question in an interview Singleton pattern guarantees creating only a single object of a class in a process or app domain level?
Jaydeep Shil
  • 1,894
  • 22
  • 21