一:介绍
定义:确保一个类只有一个实例,并提供一个全局访问点
单例模式是最简单的设计模式之一,属于创建型模式。计算机中的任务管理器,回收站是单例的典型应用场景
注意:
1、单例类只能有一个实例
2、单例类必须自己创建自己的唯一实例
3、单例类必须给所有其他对象提供这一实例
二:几种单例模式的写法
——饿汉式:在调用Instance对象之前就实例化对象
using System;
using UnityEngine;
public class Singleton : MonoBehaviour
{
//继承MonoBehaviour
private static Singleton _instance;
public static Singleton Instance
{
get { return _instance; }
}
private void Awake()
{
_instance = this;
}
// //不继承MonoBehaviour
// private static Singleton _instance = new Singleton();
// public static Singleton Instance
// {
// get { return _instance; }
// }
}
——懒汉式:在调用Instance对象之后才实例化对象
using System;
using UnityEngine;
public class Singleton : MonoBehaviour
{
//继承MonoBehaviour
private static Singleton _instance;
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<Singleton>();
}
return _instance;
}
}
// //不继承MonoBehaviour
// private static Singleton _instance;
// public static Singleton Instance
// {
// get
// {
// if (_instance == null)
// {
// _instance = new Singleton();
// }
// return _instance;
// }
// }
}
三:单例模版
——单例类模板(继承MonoBehaviour)
using UnityEngine;
public abstract class MonoSingleton<T> : MonoBehaviour
where T : MonoBehaviour
{
private static T m_Ins = null;
public static T Ins
{
get
{
if (m_Ins == null)
{
m_Ins = FindObjectOfType(typeof(T)) as T;
if (m_Ins == null)
{
m_Ins = new GameObject(typeof(T).ToString(), typeof(T)).GetComponent<T>();
var root = GameObject.Find("MonoSingleton");
if (root == null)
{
root = new GameObject("MonoSingleton");
DontDestroyOnLoad(root);
}
m_Ins.transform.parent = root.transform;
}
}
return m_Ins;
}
}
}
——单例类模板(不继承MonoBehaviour)
public abstract class Singleton<T>
where T : class, new()
{
static T m_Ins;
public static T Ins
{
get
{
if (m_Ins == null)
{
m_Ins = new T();
}
return m_Ins;
}
}
protected Singleton()
{
Init();
}
public virtual void Init()
{
}
public static void Destroy()
{
m_Ins = null;
}
}