用来批量创建重复对象,同时还要保证性能
在单例模式的基础上,创建实例时,采用内存拷贝。但是要注意浅拷贝、深拷贝的问题
public class SingletonPropoType
{
public int Id { get; set; }
public string? Name { get; set; }
private SingletonPropoType() //构造函数--耗时好资源---创建对象 执行构造函数
{
long iResut = 0;
for (int i = 0; i < 100_000_000; i++)
{
iResut++;
}
Thread.Sleep(1000); //耗时间
Console.WriteLine($"{typeof(SingletonPropoType).Name}被构造。。。");
}
static SingletonPropoType()
{
_Singleton=new SingletonPropoType();
}
private static SingletonPropoType _Singleton;
/// <summary>
/// 创建实例的时候。
/// </summary>
/// <returns></returns>
public static SingletonPropoType CreateInstance()
{
//注意,这是浅拷贝
return (SingletonPropoType)_Singleton.MemberwiseClone(); ;
}
public void Show()
{
Console.WriteLine("SingletonPropoType.show");
}
public static void Test()
{
Console.WriteLine("this is Test...");
}
}
解决浅拷贝的问题思路:
1、将里面引用类型的重新赋值,如下
注意一下特殊的引用类型,string
2、通过序列化、反序列化的方式做深拷贝