设计模式-单例模式

// See https://aka.ms/new-console-template for more information
//设计模式-单例模式
//目的:唯一性,内存资源,GCtffu
//保证整个系统中一个类只有一个对象的实例


using System.Threading.Channels;

Singleton.GetInstance().GetGuid();
Singleton.GetInstance().GetGuid();
Singleton.GetInstance().GetGuid();


class Singleton
{
    private Guid _guid;
    private static Singleton _instance;
    private Singleton()
    {
        _guid = Guid.NewGuid();

    }
    public static Singleton GetInstance()
    {
        if (_instance is null)
        {
            _instance = new Singleton();
        }
        return _instance;
    }
    public void GetGuid() => Console.WriteLine(_guid);
}

下面是在并发情况下的运行情况,并不能保证是一个单例

// See https://aka.ms/new-console-template for more information
//设计模式-单例模式
//目的:唯一性,内存资源,GCtffu
//保证整个系统中一个类只有一个对象的实例


using System.Net.Http.Headers;
using System.Threading.Channels;

//Singleton.GetInstance().GetGuid();
//Singleton.GetInstance().GetGuid();
//Singleton.GetInstance().GetGuid();

//并发情况下,并不能保证每次创建的是同一个实例
Parallel.For(0, 3, index =>
{
   var id = Singleton.GetInstance().GetGuid();
Console.WriteLine($"第{index}次:{id}");
});


class Singleton
{
   private Guid _guid;
   private static Singleton _instance;
   private Singleton()
   {
       _guid = Guid.NewGuid();

   }
   public static Singleton GetInstance()
   {
       if (_instance is null)
       {
           _instance = new Singleton();
       }
       return _instance;
   }
   public Guid GetGuid() => _guid;
  
}

第2次:1624c990-26e5-4c73-add1-fc3b736c1059
第0次:7782f74d-9100-4115-9d37-c5a2cd40f481
第1次:2ab01b9a-48c3-45af-b613-ced3def060b5

img

加入锁机制后,并发情况下,可保证每次创建的是同一个实例

// See https://aka.ms/new-console-template for more information
//设计模式-单例模式
//目的:唯一性,内存资源,GCtffu
//保证整个系统中一个类只有一个对象的实例


using System.Net.Http.Headers;
using System.Threading.Channels;

//Singleton.GetInstance().GetGuid();
//Singleton.GetInstance().GetGuid();
//Singleton.GetInstance().GetGuid();

//加入锁机制后,并发情况下,可保证每创建的是同一个实例
Parallel.For(0, 30, index =>
{
    var id = Singleton.GetInstance().GetGuid();
    Console.WriteLine($"第{index}次:{id}");
});


class Singleton
{
    private Guid _guid;
    //锁对象
    private static readonly object balanceLock = new object();//锁对象
    private static bool _instanceLock = false;
    private static Singleton? _instance;
    private Singleton()
    {
        _guid = Guid.NewGuid();

    }
    public static Singleton GetInstance()
    {
        if (_instance is null)
        {
            //lock 语句 - 确保对共享资源的独占访问权限
            lock (balanceLock)
            {


                if (_instance is null)
                {
                    _instance = new Singleton();
                }
            }
        }
        return _instance;
    }
    public Guid GetGuid() => _guid;

}
posted @ 2023-11-05 10:58  峰圣榜  阅读(5)  评论(0编辑  收藏  举报