当前位置: 首页 > article >正文

继承实现单例模式的探索(一)

前言

之前看到朋友采用继承的方式来实现单例模式,觉得很厉害,随后自己去探索了一番,以前实现单例模式都是把代码内联到具体的类中,这使得工程中每次需要使用单例模式时,都采用拷贝的方式,增加了很多冗余代码,并且难以规范单例的统一标准,使得代码不方便扩展和管理。这次探索找到了一种实现方式,先记录下来,后续如果有其它方式再发表系列文章,示例代码为C#。

代码

v1.0版本

using System;

/// <summary>
/// 单例模式基类
/// </summary>
/// <typeparam name="T">单例类型</typeparam>
public abstract class Singleton<T>
where T : class, new()
{
    public static T instance => _instance.Value;
    static bool _unlock;
    static readonly Lazy<T> _instance = new Lazy<T>(() =>
    {
        _unlock = true;
        return new T();
    });

    protected Singleton()
    {
        if (!_unlock)
            throw new InvalidOperationException("Singleton:The ctor is proxied by singleton and cannot be called from outside.");
        _unlock = false;
    }
}

v1.1 

using System;

/// <summary>
/// 单例模式基类
/// </summary>
/// <typeparam name="T">单例类型</typeparam>
public abstract class Singleton<T>
where T : class, new()
{
    public static T instance => _instance.Value;
    static bool _unlock;
    static readonly Lazy<T> _instance = new Lazy<T>(Create);

    static T Create()
    {
        _unlock = true;
        T item = new T();
        _unlock = false;
        return item;
    }

    protected Singleton()
    {
        if (!_unlock)
            throw new InvalidOperationException("Singleton:The ctor is proxied by singleton and cannot be called from outside.");
    }
}

测试

单例基类

using System;

/// <summary>
/// 单例模式基类
/// 版本1.0
/// </summary>
/// <typeparam name="T">单例类型</typeparam>
// public abstract class SingletonWithTest<T>
// where T : class, new()
// {
//     public static T instance => _instance.Value;
//     static bool _unlock;
//     static readonly Lazy<T> _instance = new Lazy<T>(() =>
//     {
//         _unlock = true;
//         return new T();
//     });

//     protected SingletonWithTest()
//     {
//         if (!_unlock)
//         {
//             // throw new InvalidOperationException("Singleton:The ctor is proxied by singleton and cannot be called from outside.");
//             Console.WriteLine($"Singleton({GetHashCode()}):The ctor is proxied by singleton and cannot be called from outside.");
//             return;
//         }
//         _unlock = false;
//         Console.WriteLine("*************************");
//     }
// }

/// <summary>
/// 单例模式基类
/// 版本1.1
/// </summary>
/// <typeparam name="T">单例类型</typeparam>
public abstract class SingletonWithTest<T>
where T : class, new()
{
    public static T instance => _instance.Value;
    static bool _unlock;
    static readonly Lazy<T> _instance = new Lazy<T>(Create);

    static T Create()
    {
        _unlock = true;
        T item = new T();
        _unlock = false;
        return item;
    }

    protected SingletonWithTest()
    {
        if (!_unlock)
        {
            // throw new InvalidOperationException("Singleton:The ctor is proxied by singleton and cannot be called from outside.");
            Console.WriteLine($"Singleton({GetHashCode()}):The ctor is proxied by singleton and cannot be called from outside.");
            return;
        }
        Console.WriteLine("*************************");
    }
}

单例继承类

public class TestA : SingletonWithTest<TestA>
{
    public readonly string key;

    public TestA() { key = "Default A"; }
    public TestA(string key) { this.key = key; }
}

public class TestB : SingletonWithTest<TestB>
{
    public readonly string key;

    public TestB() { key = "Default B"; }
    public TestB(string key) { this.key = key; }
}

public class TestC : SingletonWithTest<TestC>
{
    public readonly string key;

    public TestC() { key = "Default C"; }
    public TestC(string key) { this.key = key; }
}

public class TestD : SingletonWithTest<TestD>
{
    public readonly string key;

    public TestD() { key = "Default D"; }
    public TestD(string key) { this.key = key; }
}

public class TestE : SingletonWithTest<TestE>
{
    public readonly string key;

    public TestE() { key = "Default E"; }
    public TestE(string key) { this.key = key; }
}

public class TestF : SingletonWithTest<TestF>
{
    public readonly string key;

    public TestF() { key = "Default F"; }
    public TestF(string key) { this.key = key; }
}

测试代码

// ********************************* 创建实例测试:通过 ********************************* 

// 直接创建实例测试:通过
// TestA a = new TestA(); // 无法通过 new + 无参ctor 创建实例
// TestA a1 = new TestA("A1"); // 无法通过 new + 有参ctor 创建实例
// TestA a2 = Activator.CreateInstance<TestA>(); // 无法通过 Activator 创建实例
// TestA? a2 = Activator.CreateInstance(typeof(TestA), "A1") as TestA; // 无法通过 Activator 创建实例

// ********************************* 线程安全测试:通过 *********************************

Thread t1, t2, t3, t4, t5, t6;

// 打印同一单例的 HashCode 测试:通过
t1 = new Thread(() => Console.WriteLine("Thread1:" + TestA.instance.GetHashCode()));
t2 = new Thread(() => Console.WriteLine("Thread2:" + TestA.instance.GetHashCode()));
t3 = new Thread(() => Console.WriteLine("Thread3:" + TestA.instance.GetHashCode()));
t4 = new Thread(() => Console.WriteLine("Thread4:" + TestA.instance.GetHashCode()));
t5 = new Thread(() => Console.WriteLine("Thread5:" + TestA.instance.GetHashCode()));
t6 = new Thread(() => Console.WriteLine("Thread6:" + TestA.instance.GetHashCode()));

// 使用单例的同时直接创建该单例类型实例测试:通过
// t1 = new Thread(() => Console.WriteLine("Thread1:" + TestA.instance.GetHashCode()));
// t2 = new Thread(() => Console.WriteLine("Thread2:" + new TestA().GetHashCode()));
// t3 = new Thread(() => Console.WriteLine("Thread3:" + new TestA().GetHashCode()));
// t4 = new Thread(() => Console.WriteLine("Thread4:" + new TestA().GetHashCode()));
// t5 = new Thread(() => Console.WriteLine("Thread5:" + new TestA().GetHashCode()));
// t6 = new Thread(() => Console.WriteLine("Thread6:" + new TestA().GetHashCode()));

// 同时使用不同单例的测试:通过
// t1 = new Thread(() => Console.WriteLine("Thread1:" + TestA.instance.GetHashCode()));
// t2 = new Thread(() => Console.WriteLine("Thread2:" + TestB.instance.GetHashCode()));
// t3 = new Thread(() => Console.WriteLine("Thread3:" + TestC.instance.GetHashCode()));
// t4 = new Thread(() => Console.WriteLine("Thread4:" + TestD.instance.GetHashCode()));
// t5 = new Thread(() => Console.WriteLine("Thread5:" + TestE.instance.GetHashCode()));
// t6 = new Thread(() => Console.WriteLine("Thread6:" + TestF.instance.GetHashCode()));

// 使用单例的同时创建其它单例类型的实例测试:通过
// t1 = new Thread(() => Console.WriteLine("Thread1:" + TestA.instance.GetHashCode()));
// t2 = new Thread(() => Console.WriteLine("Thread2:" + new TestB().GetHashCode()));
// t3 = new Thread(() => Console.WriteLine("Thread3:" + new TestC().GetHashCode()));
// t4 = new Thread(() => Console.WriteLine("Thread4:" + new TestD().GetHashCode()));
// t5 = new Thread(() => Console.WriteLine("Thread5:" + new TestE().GetHashCode()));
// t6 = new Thread(() => Console.WriteLine("Thread6:" + new TestF().GetHashCode()));

t1.Start();
t2.Start();
t3.Start();
t4.Start();
t5.Start();
t6.Start();

t1.Join();
t2.Join();
t3.Join();
t4.Join();
t5.Join();
t6.Join();

优缺点分析

优点

1.通过继承实现单例;

2.可以通过单例基类规范统一标准;

3.线程安全;

4.无法通过除单例基类提供的静态属性instance以外的其它方式获取其派生类实例,外部通过new关键字显示调用构造函数或反射等其它获取实例的方式创建派生类实例将触发异常;

5.派生类的无参构造函数用于初始化;

6.按需加载,延迟初始化。

缺点

1.要求派生类的无参构造函数公开;

2.派生类对外部始终开放无参构造函数,无法避免new关键字的显式调用所触发的异常; 

版本改进

V1.1

1.将延迟初始化的工厂方法从Lambda表达式替换为本地静态方法,因为_unlock相对于Lazy<T>是外部引用,所以不可避免存在创建闭包的开销,所以改为本地静态方法进行改进;

2._unlock在构造函数中进行重置会存在线程安全的问题,放在作为延迟初始化的工厂方法的本地静态方法中可以保证线程安全。

......

系列文章

继承实现单例模式的探索(二)

如果这篇文章对你有帮助,请给作者点个赞吧!


http://www.kler.cn/news/328894.html

相关文章:

  • 已解决:“ModuleNotFoundError:No module named apex”
  • Vue3+Antv X6流程图基本使用
  • 蓝桥杯【物联网】零基础到国奖之路:十六. 扩展模块之矩阵按键
  • 智能工厂的设计软件 三部曲-表征模式mode(大纲图轮廓图和草图)之1 “草图”--基类基元:“概念对子Pair
  • [leetcode]300_最长递增子序列
  • HTTP Status 404 - /brand-demo/selectAllServlet错误解决原因-Servlet/JavaWeb/IDEA
  • Spring异常处理-@ExceptionHandler-@ControllerAdvice-全局异常处理
  • ue4多个面重叠闪烁
  • ubuntu18.04 Anconda安装及使用
  • 【网络安全】-访问控制-burp(1~6)
  • 在idea使用nacos微服务
  • LeetCode[中等] 45. 跳跃游戏 II
  • 排序算法的理解
  • 【ChatGPT】Python 实现计算两线段的变换矩阵
  • 解决Windows远程桌面 “为安全考虑,已锁定该用户账户,原因是登录尝试或密码更改尝试过多,请稍后片刻再重试,或与系统管理员或技术支持联系“问题
  • 师生健康监测系统:SpringBoot技术实践
  • Master PDF Editor 下载及详细安装教程
  • Codeforces Round 976 (Div. 2 ABCDE题)视频讲解
  • Django一分钟:使用prefetch_related避免陷入大量的查询中导致严重的性能问题
  • WebGL深究:动画与交互 —— 赋予虚拟世界生命与灵魂
  • YOLOv11尝鲜测试五分钟极简配置
  • SpringBoot整合JPA详解
  • 工控系统组成与安全需求分析
  • leetcode每日一题day21(24.10.1)——最低票价
  • Street View Synthesis with Gaussian Splatting and Diffusion Prior 学习笔记
  • 【Java SE 题库】移除元素(暴力解法)--力扣
  • 室内定位论文整理-20240925期
  • 计算机毕业设计党建学习网站查看发布党建评论留言搜索部署安装/springboot/javaWEB/J2EE/MYSQL数据库/vue前后分离小程序
  • 【SpringCloud】多机部署, 负载均衡-LoadBalance
  • 使用 Seaborn 热图的 5 种方法(Python 教程)