// 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