单例模式为什么被发明出来?
博客园“只要爱你”——《单例和静态类的区别》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层级视图的游戏物体上,自己生成的游戏物体,也贴有同样的“高级单例”脚本,层级视图就会有两个此脚本,也就不是单例了。