ホーム -> デザインパターンのスケルトン
prev UML クラス図解説サイト with C# 前へ UML クラス図解説サイト with C# トップへ UML クラス図解説サイト with C# 次へ next

シングルトン

class Program
{
    static void Main(string[] args)
    {
        Thread t1 = new Thread(new ThreadStart(ThreadProc1));
        Thread t2 = new Thread(new ThreadStart(ThreadProc2));

        t1.Start();
        t2.Start();

        t1.Join();
        t2.Join();
        
        Console.ReadLine();
    }

    public static void ThreadProc1()
    {
        for (int i = 0; i < 10; i++)
        {
            Singleton.Instance.IntCnt += 1;
            Console.WriteLine("Proc1:" + Singleton.Instance.IntCnt);
        }
    }
    public static void ThreadProc2()
    {
        for (int i = 0; i < 10; i++)
        {
            Singleton.Instance.IntCnt += 1;
            Console.WriteLine("Proc2:" + Singleton.Instance.IntCnt);
        }
    }
}
public sealed class Singleton
{
    private static volatile Singleton instance;
    private static object syncRoot = new Object();

    private Singleton() { }

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

            return instance;
        }
    }

    private int intCnt;
    public int IntCnt
    {
        get { return intCnt; }
        set { intCnt = value; }
    }
}

prev UML クラス図解説サイト with C# 前へ UML クラス図解説サイト with C# トップへ UML クラス図解説サイト with C# 次へ next
inserted by FC2 system