天天看點

Singleton模式(一) - 簡單多線程計數器

1. 經典的設計模式中的代碼

public class Singleton

    {

        private static Singleton instance;   // 唯一執行個體

        protected Singleton() { }   // 封閉客戶程式的直接執行個體化

        public static Singleton Instance    

        {

            get

            {

                if (instance == null)

                    instance = new Singleton();

                return instance;

            }

        }

    }

  在多線程環境下存在缺陷, 最終将會儲存最後建立的那個執行個體

2. 改進後的多線程Singleton

class Singleton

        private Singleton() { }

        [ThreadStatic]

        public static readonly Singleton Instance = new Singleton();

3. 線程計數器

public class ThreadCounter

        private ThreadCounter() { }

        public static readonly ThreadCounter Instance = new ThreadCounter();

        private int value;

        public int Next { get { return ++value; } }

        public void Reset() { value = 0; }

4. 調用代碼

  ThreadCounter.Instance.Next

繼續閱讀