设计模式十八(单例模式)

1.个人感觉就是只能为一个类创建一个对象的场合使用

 

2.代码展示

 

namespace 单例模式
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton s1 = Singleton.GetInstance();
            Singleton s2 = Singleton.GetInstance();

            if (s1 == s2)
            {
                Console.WriteLine("Objects are the same instance");
            }

            Console.Read();
        }
    }


    class Singleton
    {
        private static Singleton instance;
        private Singleton()
        {
        }

        public static Singleton GetInstance()
        {
            if (instance == null)
            {

                instance = new Singleton();
             }

             return instance;
         }
       }

    }

 

 

3.多线程的单例模式(懒汉式)

 

namespace 单例模式
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton s1 = Singleton.GetInstance();
            Singleton s2 = Singleton.GetInstance();

            if (s1 == s2)
            {
                Console.WriteLine("Objects are the same instance");
            }

            Console.Read();
        }
    }


    class Singleton
    {
        private static Singleton instance;
        private static readonly object syncRoot = new object();//用于锁定
        private Singleton()
        {
        }

        public static Singleton GetInstance()//方法里面用了双重锁定
        {
            if (instance == null)//当不为空的时候直接调用
            {

                lock (syncRoot)//否则锁定。但是这里有可能同时进来了2或以上个进程,所以在里面在进行空的判断
                {

                    if (instance == null)//这里就是当有多个进程进入的时候判断是否已经有进程创建了对象
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }

    }

 

4.多线程的单例模式(饿汉式)

 

namespace 单例模式
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton s1 = Singleton.GetInstance();
            Singleton s2 = Singleton.GetInstance();

            if (s1 == s2)
            {
                Console.WriteLine("Objects are the same instance");
            }

            Console.Read();
        }
    }

 

//这种在类的初始化的时候就直接产生一个实例,而上一个则是在系统运行时
    public sealed class Singleton   {
        private static readonly Singleton instance = new Singleton();
        private Singleton() { }
        public static Singleton GetInstance()
        {
            return instance;
        }
    }
}

 

posted @ 2010-12-01 00:14  yu_liantao  阅读(153)  评论(0)    收藏  举报