基于静态Singleton模式的使用介绍
- 作者: 鑫少爷37133862
- 来源: 51数据库
- 2021-08-22
什么是静态单例模式?
静态单例模式(static singleton pattern)是我在实践中总结的模式,主要解决的问题是在预先知道某依赖项为单例应用时,通过静态缓存该依赖项来提供访问。当然,解决该问题的办法有很多,这只是其中一个。
实现细节
/// <summary>
/// 静态单例
/// </summary>
/// <typeparam name="tclass">单例类型</typeparam>
public static class singleton<tclass> where tclass : class, new()
{
private static readonly object _lock = new object();
private static tclass _instance = default(tclass);
/// <summary>
/// 获取单例实例
/// </summary>
public static tclass getinstance()
{
return instance;
}
/// <summary>
/// 单例实例
/// </summary>
public static tclass instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
_instance = new tclass(); // must be public constructor
}
}
}
return _instance;
}
}
/// <summary>
/// 设置单例实例
/// </summary>
/// <param name="instance">单例实例</param>
public static void set(tclass instance)
{
lock (_lock)
{
_instance = instance;
}
}
/// <summary>
/// 重置单例实例
/// </summary>
public static void reset()
{
lock (_lock)
{
_instance = default(tclass);
}
}
}
应用测试
class program
{
interface iinterfacea
{
string getdata();
}
class classa : iinterfacea
{
public string getdata()
{
return string.format("this is from classa with hash [{0}].", this.gethashcode());
}
}
static void main(string[] args)
{
string data1 = singleton<classa>.getinstance().getdata();
console.writeline(data1);
string data2 = singleton<classa>.getinstance().getdata();
console.writeline(data2);
console.readkey();
}
}
测试结果

- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
