Walden1024

导航

《大话设计模式》学习笔记17:单例模式

  

  

实现:

1.Singleton:

    public class Singleton
    {
        private static Singleton instance;
        //构造方法为private,外部代码不能直接实例化
        private Singleton()
        {

        }

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

2.客户端代码:

    class Program
    {
        static void Main(string[] args)
        {
            Singleton singleton1 = Singleton.GetInstance();
            Singleton singleton2 = Singleton.GetInstance();

            if(singleton1==singleton2)
            {
                Console.WriteLine("两个对象是相同的实例。");
            }
            else
            {
                Console.WriteLine("两个对象是不同的实例。");
            }
        }
    }

 

多线程时的单例:

1.lock:

    public class Singleton
    {
        private static Singleton instance;
        private static readonly object syncRoot = new object();
        private Singleton()
        {

        }

        public static Singleton GetInstance()
        {
            lock(syncRoot)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
            }
            return instance;
        }
    }

2.双重锁定:

    public class Singleton
    {
        private static Singleton instance;
        private static readonly object syncRoot = new object();
        private Singleton()
        {

        }

        public static Singleton GetInstance()
        {
            if(instance==null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }

 

静态初始化:

    public sealed class Singleton//sealed阻止发生派生,因为派生可能会增加实例
    {
        private static readonly Singleton instance = new Singleton();
        private Singleton()
        {

        }

        public static Singleton GetInstance()
        {
            return instance;
        }
    }

 

静态初始化的方式在自己被加载时就将自己实例化,称之为恶汉式单例类;之前的单例模式是在第一次被引用时才会将自己实例化,称为懒汉单例类。

posted on 2015-05-21 22:09  Walden1024  阅读(303)  评论(2编辑  收藏  举报