不继承Mono的单例模式基类

1. 为什么要写写单例模式基类

用面向对象的思想避免代码冗余(多余、重复)

2. 实现不继承MonoBehaviour的单例模式基类

单例模式的基类

csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 单例模式基类,主要目的是避免代码的冗余,方便实现单例模式的类
/// </summary>
/// <typeparam name="T"></typeparam>
//where约束T必须是class,还有有一个公共的无参构造函数
public class BaseManager<T> where T : class,new()
{
    public static T instance;

    // 属性的方式
    public static T Instance
    {
        get
        {
            if(instance == null)
            {
                instance = new T();
            }
            return instance;
        }
    }

    // 方法的方式
    public static T GetInstance()
    {
        if(instance == null)
        {
            instance = new T();
        }
        return instance;
    }
}

当其他类需要实现单例时候,直接继承基类

csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestMgr : BaseManager<TestMgr>
{

    public void TestLog()
    {
        Debug.Log("Test");

    }
    
}

好处就是可以避免代码冗余,不用重复定义单例,需要单例直接继承就行

csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestMgr2 : BaseManager<TestMgr2>
{
    public void TestLog()
    {
        Debug.Log("test2");
    }
    
}

测试

csharp 复制代码
public class Main : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        TestMgr.Instance.TestLog();
        TestMgr2.Instance.TestLog();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

3. 潜在的安全问题

1.构造函数问题:构造函数可在外部调用 可能会破坏唯一性

比如csharp TestMgr t = new TestMgr(); 不能new一个单例模式的对象,可以通过反射解决

2.多线程问题:当多个线程同时访问管理器时,可能会出现共享资源的安全访问问题

相关推荐
阿拉斯攀登5 分钟前
20 个 Android JNI + CMake 生产级示例
android·java·开发语言·人工智能·机器学习·无人售货柜
空中海17 分钟前
第十一章:Kotlin 进阶与 Android 原理
android
studyForMokey27 分钟前
【Android面试】设计模式专题
android·设计模式·面试
三少爷的鞋35 分钟前
别再写 BaseXXX 了:BaseActivity 和 BaseViewModel 正在毁掉你的架构
android
Trustport39 分钟前
ArcGIS Maps SDK For Kotlin 加载Layout中的MapView出错
android·开发语言·arcgis·kotlin
EQ-雪梨蛋花汤1 小时前
【笔记】安卓毛玻璃效果(Blur)实现笔记(使用BlurView)(结尾附:源码)
android·笔记
StackNoOverflow3 小时前
MySQL Explain 返回列详解:从入门到实战,附 SQL 与避坑大全
android
CYRUS_STUDIO11 小时前
Frida 检测与对抗实战:进程、maps、线程、符号全特征清除
android·逆向
csj5012 小时前
安卓基础之《(28)—Service组件》
android
lhbian14 小时前
PHP、C++和C语言对比:哪个更适合你?
android·数据库·spring boot·mysql·kafka