单例模式就是指单例类在一定的生命周期内只能有一个对象实例,单例类的创建必须是本身,并能给使用者提供自身。
在现实世界中,每个生命体都可以被看做是一个单例对象,唯一且具体,具有不可复制性。同样的,在软件开发领域中,有时我们需要保证客户端在当前的客户机上只能运行一个实例这个时候,我们就应该考虑使用单例模式来实现这种业务场景。
略
1、懒汉式,线程不安全
public class singleobject { private static singleobject _instance; private singleobject() { } public static singleobject getinstance() => _instance ?? (_instance = new singleobject()); public void showmessage() { console.writeline("hello world"); } }
2、懒汉式,线程安全
public class singleobject { private static singleobject _instance; private static readonly object _locker = new object(); private singleobject() { } public static singleobject getinstance() { if (_instance == null) { lock (_locker) { if (_instance == null) { _instance = new singleobject(); } } } return _instance; } public void showmessage() { console.writeline("hello world"); } }
3、静态内部类延迟加载
public class singleobject { public static singleobject getinstance() => nested.instance; private sealed class nested { static nested() { } internal static readonly singleobject instance = new singleobject(); } public void showmessage() { console.writeline("hello world"); } }
4、上层调用
class program { static void main(string[] args) { singleobject.getinstance().showmessage(); console.readkey(); } }
对于单例模式,较为好理解,如果需要保持对象的唯一性,则可以考虑使用这种模式进行解决。
如对本文有疑问, 点击进行留言回复!!
荐 厉害了!阿里P8架构师用4大技术文档带你深入解读爆火的中台战略
FlowableException: Error initialising dmn data model报错问题
网友评论