脚本宝典收集整理的这篇文章主要介绍了单例模式的三种写法,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
单例模式是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; } } }
以上是脚本宝典为你收集整理的单例模式的三种写法全部内容,希望文章能够帮你解决单例模式的三种写法所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。