【单例模式】普通单例+懒汉单例+高端单例——定义单例类的同时,生成一个物体(添加该单例类脚本)

单例模式为什么被发明出来?

博客园“只要爱你”——《单例和静态类的区别》https://www.cnblogs.com/lycfuture-66/p/10788954.html

普通单例


using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class NormalSingleton : MonoBehaviour
{
    private static NormalSingleton _instance;
    public static  NormalSingleton GetInstance()
    {
        if(_instance==null)
        {
            _instance = new NormalSingleton();
        }
        return _instance;
    }
}

懒汉单例

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class LazySingleton : MonoBehaviour
{
    public static LazySingleton _instance;
    void Awake()
    {
        _instance = this;
    }

  
}

高级单例

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class AddSelfToSelfCreatedGOSingleton : MonoBehaviour
{
    private static AddSelfToSelfCreatedGOSingleton _instance;
    public static AddSelfToSelfCreatedGOSingleton GetInstance()
    {
        if (_instance == null)
        {
            _instance = new GameObject("该单例脚本生成、贴有该单例脚本的游戏物体").AddComponent<AddSelfToSelfCreatedGOSingleton>();
        }
        return _instance;
    }
}
调用

在三种单例中分别定义三个变量,然后其它的类调用这三个变量
public int varX=333;
public int varY=666;
public int varZ= 999;

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class CallSingletonVarOrFunc : MonoBehaviour
{
  
    void Start()
    {
        Debug.Log(NormalSingleton.GetInstance().varX);
        Debug.Log(LazySingleton._instance.varY);
        Debug.Log(AddSelfToSelfCreatedGOSingleton.GetInstance().varZ);

    }


注意

“高级单例”脚本,不加到层级视图Hirarchy的游戏物体上,而是其它脚本调用其中的变量或方法时,自动在层级视图中生成一个贴有“高级单例”脚本的物体——如果添加到Hirarchy层级视图的游戏物体上,自己生成的游戏物体,也贴有同样的“高级单例”脚本,层级视图就会有两个此脚本,也就不是单例了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值