utorok, 01 november 2016 08:47 Written by 2333 times
Rate this item
(1 Vote)

C# - Implementácia Singleton Patternu

Singleton je jedným z najznámejších návrhových vzorov. Singleton je trieda, ktorá dovoli vytvoriť iba jednu inštanciu samej seba. Využijeme ho pri riešení problémov, kedy je potrebné, aby v celom programe bežala iba jedna inštancia triedy. Poskytne k nej globálny prístupový bod.

Kód v c# (not thread-safe):

// Bad code! Do not use!
public sealed class Singleton
{
    private static Singleton instance=null;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
} 

Kód v c# (simple thread-safety):

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

Kód v c# (thread-safety using double-check locking):

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
} 

 

Kód v c# (Using .NET 4's Lazy type):

 

public sealed class Singleton
{
    private Singleton()
    {

    }

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

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

 

 

Last modified on utorok, 01 november 2016 09:21
Ing.Jaroslav Vadel

Som zakladateľom www.projectik.eu.

Hrám sa na programátora, ktorý ovláda:

c#,cpp,java,unity3d,php,html,NI testand,NI Vision Builder,Cognex In-Sight,NI LabView

"Naprogramovať program, ktorý funguje vie každy. Ale to, že program funguje ešte neznamena, že je napísany správne "

Website: www.projectik.eu