单例模式就自己理解

单例模式在Unity中常用于简化脚本间交互,提高代码维护性。通过确保类只有一个实例并提供全局访问点,实现资源的有效管理。文章探讨了单例的特点,包括唯一性、自我实例化和静态方法获取实例。同时,指出了简单的引用和继承方法可能存在的线程安全问题,并提出了双锁实现的懒汉模式作为解决方案,以及通过继承实现的管理模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为什么要出现单例化?

在unity中,会不可避免地出现各脚本之间的交互,但交互过多,会使得代码的维护变得非常麻烦。为了减少消耗,一般都是声明一个全局脚本并声明一个全局变量,让各脚本之间的交互变成与此仅一例脚本交互。一般用于管理系统。

单例化的特点

1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例,以静态方法获取。

就我而言,单例化的简单方法

public class A
{
    public static A instance;
    void Awake()
    {
    	instance = this;
    }
 }

为了确保唯一性

public class A
{
    public static A instance;
    void Awake()
    {
    if(instance == null)
     instance = this;
     return;
    }
 }

在unity中,单例化简单的引用为引用、继承方法。例如引用。声明两个脚本,在B中引用A的bool值。

public class A
{
    public static A instance;
    public bool EXA;
    void Awake()
    {
    if(instance == null)
     instance = this;
     return;
    }
 }

public class B
{
    public static B instance;
    void Awake()
    {
    if(instance == null)
     instance = this;
     return;
    }
    void Update()
    {
    if(A.instance.EXA)
    {
    Debug.Log("1");
    }
 }

在这里插入图片描述可修改值(?)

public class A
{
    public static A instance;
    public bool EXA = true;
    void Awake()
    {
    if(instance == null)
     instance = this;
     return;
    }
 }
 public class B
{
    public static B instance;
    void Awake()
    {
    if(instance == null)
     instance = this;
     return;
    }
    void Update()
    {
    A.instance.EXA = false;
    }
 }

在这里插入图片描述
但是,这样子的单例化线程并不安全,在开启另一个线程时,系统检测不到instance的存在,会出现创建一个单例,这样子,每一个线程都会创建单例。

借鉴于网上的更加好的方法,但是性能消耗大

public class A 
{      
private static A instance;    
private A (){}       
public static A getInstance()
{      
    if (instance == null) 
{         
    instance = new A(); 
}     
    return instance;     
}
}  

双锁(懒汉模式的一种),性能消耗更小

public class A
{
private volatile A instance = null;
private A(){}      
public static A getInstance(){
if(instance == null){
synchronized (A.class){
if(instance == null){
instance = new A();
}
}
}
return instance;
}
}

管理模式,省去重复单例化,直接继承

public class A <T> where T :new()
{
private volatile T instance = null;
private T (){}//?      
public static T getInstance(){
if(instance == null){
synchronized (T.class){
if(instance == null){
instance = new T();
}
}
}
return instance;
}
}

public class B : A <B>
{
}

小新见解,有错敬请大佬纠正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值