2025-03-28 09:49:56 +08:00

70 lines
2.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using SuperMap.RealEstate.ServiceModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EShang.Common
{
/*
* 单例模式Singleton 泛型
* 定义:单例模式的意思就是只有一个实例(整个应用程序的生命周期中)。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。(百度百科~~
* 要点: 一是某个类只能有一个实例;
* 二是它必须自行创建这个实例;
* 三是它必须自行向整个系统提供这个实例。
* create zhengxp 2020-10-20
*/
/// <summary>
/// 多线程下的单例模式(Lazy模式)Singleton 泛型
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingleBase<T> where T : class //new()new不支持非公共的无参构造函数
{
#region
/*
* 单线程测试通过!
* 多线程测试通过!
* 根据需要在调用的时候才实例化单例类!
*/
//定义一个静态变量来保存类的实例
private static T _instance;
/// <summary>
/// 定义一个标识确保线程同步
/// </summary>
public static readonly object SyncObject = new object();
/// <summary>
/// 定义公有方法提供一个全局访问点,同时你也可以定义公有属性来提供全局访问点
/// </summary>
/// <param name="transaction">事务</param>
/// <returns></returns>
public static T GetInstance(Transaction transaction)
{
if (_instance == null)//没有第一重 singleton == null 的话,每一次有线程进入 GetInstance()时,均会执行锁定操作来实现线程同步,
//非常耗费性能 增加第一重singleton ==null 成立时的情况下执行一次锁定以实现线程同步
{
lock (SyncObject)
{
if (_instance == null)//Double-Check Locking 双重检查锁定
{
//_instance = new T();
//需要非公共的无参构造函数不能使用new T() ,new不支持非公共的无参构造函数
_instance = (T)Activator.CreateInstance(typeof(T), transaction); //第二个参数防止异常:“没有为该对象定义无参数的构造函数。”
}
}
}
return _instance;
}
public static void SetInstance(T value)
{
_instance = value;
}
#endregion
}
}