单例模式的三种写法

    单例模式是23设计中创建模式的第一个,也是入门的设计模式,好多net 程序员 工作7-8 你让他写3-4个设计模式,我敢说,很多人可能都写不出来,因为net 封装的太厉害了,很多程序员有种惰性,总是"约定俗成" 我就这么用的。C# 语言是一款优秀的语言,并不比java差,只是java 开源早,生态环境好。好了不废话了。直接上三中写法。

   经典写法,双if +lock ,第一个if 判断是为了节省资源,第二个判断是否已经创建对象。。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesgersClass
{
    public class singleton
    {
        private static object _lock=new object();  
        private static  singleton singletons;

        public int m = 0;
        public int add()
        { 
         return m++;
        }
        private singleton()
        {
                
        }
        public static singleton CreateIntance()
        {
            if (singletons == null)
            {
                lock (_lock)//双if +lock
                {
                    if (singletons == null)
                    {
                        singletons = new singleton();
                    }
                }
            }
            return singletons;
        }

    }
}

客户端调用时 我们不难看出虽然我们循环100次 但是 全局就一个对象,所以a是累加的。

using DesgersClass;
using System;

namespace Desgionser23
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            singleton singleton= singleton.CreateIntance();
            var a = 0;
            for (int i = 0; i < 100; i++) {
             a=   singleton.add();
                Console.WriteLine($"*******************************************");
                Console.WriteLine($"a={a}");
            }

            Console.WriteLine();
        }
    }
}

 

第二种和第三种 基本套路是一样的,都是利用底层clr 保证静态字段和静态构造函数只创建一次

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesgersClass
{
    public class singletonstaticProp
    {

        private static singletonstaticProp singletonstaticProps = new singletonstaticProp();
        public static singletonstaticProp CreateInstance()
        {
            return singletonstaticProps;
        }

    }
}

*********************

第三种

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesgersClass
{
    public class singletonstatic
    {
        private static singletonstatic singletonstatics;

        static singletonstatic()
        {
            singletonstatics = new singletonstatic();
        }

        public static singletonstatic CreateInstance()
        {
            return singletonstatics;
        }

    }
}
原文地址:https://www.cnblogs.com/jasontarry/p/15450252.html