设计模式-单例模式

单例模式:即一个类全局只有一个实例,而且自行实例化冰箱整个系统提供这个实例。

根据创建的时机可以分为饿汉式和懒汉式

懒汉式是在第一个调用这个实例时创建,饿汉式是该类在加载时立刻进行实例化

懒汉式泛型单例

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

public class ISingleton<T> where T : class, new()
{
    private static T instance = null;

    public static T Instance
    {
        get
        {
            if (instance == null)
                instance = new T();
            return instance;
        }
    }

}

饿汉式泛型单例

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

public class ISingleton<T> where T : class, new()
{
    private static T instance = new T();

    public static T Instance
    {
        get
        {
            return instance;
        }
    }

}

具体单例

cs 复制代码
class A : ISingleton<A>
{

}

缺点:

1.生命周期不可控

很多时候我们的单例是只有访问时才会加载的,属于懒汉式,这个单例的生命什么时候结束脱离了GC的掌控,只能靠我们自己去释放,如果忘记释放或者提前被释放容易产生各种问题,(其他开发者不知道你什么时候释放单例,所以就无法释放)

2.作用域过广

我们在全局都能通过静态访问单例,容易让用户误操作,而且让代码散乱不安全,如果有100个单例...这都是什么

3.单一职责过于复杂

使用单例可能会让一个类复杂多种职责,容易让单一文件过大,代码复杂性上升,一个GameManager统计分数还计时,还存玩家信息,又存地图信息...改起来亚历山大

相关推荐
咖啡八杯2 天前
GoF设计模式——策略模式
java·后端·spring·设计模式
槑有老呆3 天前
别再手搓 Prompt 了,那个叫"手动挡循环"
设计模式
用户6919026813394 天前
Vibe Coding 开发项目的基本范式
人工智能·设计模式·代码规范
怕浪猫5 天前
领域特定语言(Domain-Specific Language, DSL)
设计模式·程序员·架构
Larcher7 天前
AI Loop:让AI像人一样自主完成任务的核心机制
javascript·人工智能·设计模式
咖啡八杯8 天前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
:mnong8 天前
学习创建结构行为设计模式
设计模式
w_t_y_y8 天前
Agent设计模式(四)多模态融合模式(Multi-Modal Fusion)
设计模式