[Design Pattern] Singleton

單例模式 - Singleton

保證一個類別只會產生一個物件,而且要提供存取該物件的統一方法。

Greed Singleton - not thread-safe

/* Bad Code, Not use */
 public class SingletonGreed
    {
        private static SingletonGreed instance = new SingletonGreed();

        private SingletonGreed()
        {
            Console.WriteLine("I am Greed Singleton!");
        }

        public static SingletonGreed getInstance()
        {
            return instance;
        }
    }

Singleton - thread-safe

public class SingletonGreedSafeThread
    {
        private static SingletonGreedSafeThread instance = null;
        private static readonly Object _lock = new Object();

        private SingletonGreedSafeThread()
        {
            Console.WriteLine("I am Safe Thread Greed Singleton!");
        }

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

Singleton - Lazy

public class SingletonLazy
    {
        private static readonly Lazy<SingletonLazy> lazy = new Lazy<SingletonLazy>(()=>new SingletonLazy());
        public static SingletonLazy Instance { get; } = lazy.Value;

        private SingletonLazy()
        {
            Console.WriteLine("I am Lazy Singleton.");
        }
    }

Reference

  1. csharpindepth-Singleton
  2. xyz-Singleton

留言

這個網誌中的熱門文章

[Tools] GCOV & LCOV 初探

Quilt Patch 管理操作方法

[C#]C# Coding 規則