• C#单例模式的三种写法


    第一种最简单,但没有考虑线程安全,在多线程时可能会出问题 

    public class Singleton
    {
    private static Singleton _instance = null;
    private Singleton(){}
    public static Singleton CreateInstance()
    {
    if(_instance == null)
    {
    _instance = new Singleton();
    }
    return _instance;
    }
    }

    第二种考虑了线程安全,不过有点烦,但绝对是正规写法,经典的一叉 

    public class Singleton
    {
    private volatile static Singleton _instance = null;
    private static readonly object lockHelper = new object();
    private Singleton(){}
    public static Singleton CreateInstance()
    {
    if(_instance == null)
    {
    lock(lockHelper)
    {
    if(_instance == null)
    _instance = new Singleton();
    }
    }
    return _instance;
    }
    }

    第三种可能是C#这样的高级语言特有的,实在懒得出奇

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

    oh!shit...wt..

  • 相关阅读:
    android-layout-finder 在线生成findViewById
    Android 广播机制
    Android Service随笔
    新博客地址(https://minxin.github.io)
    angr学习(四)
    angr学习(三)
    angr学习(二)
    angr学习(一)
    android studio NDK开发方案
    python虚拟机
  • 原文地址:https://www.cnblogs.com/matong/p/2429648.html
Copyright © 2020-2023  润新知