关于单例模式的一个小demo,在多线程访问中,为了实例唯一,所以object锁定下。

 

using System;
using System.Collections.Generic;
using System.Text;

class Singleton
{

    private static object lockHelper = new object();
    private static volatile Singleton instance = null;
    private string _myName;

    public string MyName
    {
        get { return _myName; }
        set { _myName = value; }
    }

    private Singleton()
    {
        _myName = "leon";
    }

    public static Singleton GetInstance()
    {
        if (instance == null)
        {
            lock (lockHelper)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
            }
        }
        return instance;

    }

}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Singleton.GetInstance().MyName);
        Console.ReadLine();
    }
}

 

相关文章:

  • 2021-12-20
  • 2022-12-23
  • 2021-04-29
  • 2021-12-29
  • 2022-02-14
  • 2021-09-15
  • 2022-12-23
猜你喜欢
  • 2021-05-29
  • 2021-07-21
  • 2022-12-23
  • 2022-12-23
  • 2021-12-06
  • 2022-12-23
  • 2021-10-03
相关资源
相似解决方案