Feedback

Einfaches Singleton-Pattern

Sprache: C#

Implementierung eines einfaches Singleton-Pattern.

public sealed class Singleton
{
    private Singleton()
    {}

    // Dein Code hier

    public static Singleton Instance
    { 
        get { return lazy.Value; } 
    }

    private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
}

public sealed class Singleton
{
    private Singleton()
    {}

    // Dein Code hier

    public static Singleton Instance
    { 
        get { return lazy.Value; } 
    }

    private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
}

2 Kommentare

  1. @Stefan
    durch die Lazy-Klasse wird die Instanz erst erzeugt wenn man sie braucht. Alternativ könnte man auch im Getter prüfen ob die Instanz null ist und ggf. eine neue erzeugen. Mit der Lazy-Klasse ist es aber etwas moderner. Soweit die allgemeine Theorie.

    Wenn man den Parameterlosen Konstruktor aufrufen will kann man den Lambda auch einfach weg lassen. Da hast du recht. Ich halte es trotzdem für erwähnenswert falls man einen nicht parameterlosen Konstruktor oder eine ganz andere Initialisierung einbauen möchte.