全局唯一在别的类中不能被实例化,但是能全局被调用。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 第一种单利模式写法
/// </summary>
public class GameController : MonoBehaviour
{
public static GameController instance;
private void Awake()
{
instance = this;
}
}
/// <summary>
/// 第二种单利模式的写法
/// </summary>
public class GameData
{
public static GameData instance;
public static GameData GetInstance()
{
if (instance == null)
{
instance = new GameData();
}
return instance;
}
}
/// <summary>
/// 第三种写法
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class GameTemplate<T> where T : new()
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = new T();
}
return instance;
}
}
}
/// <summary>
/// 第四种写法
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance
{
get
{
return instance;
}
}
protected virtual void Awake()
{
instance = this as T;
}
}
/// <summary>
/// 第五种
/// 同一时间内部分,程序只有一个线程进入实例化,后来的需要排队等待前一个结束
/// 增加了额外开销,损失性能,但是可保证线程安全
/// </summary>
public sealed class ThreadSingleton
{
static ThreadSingleton instance = null;
private static readonly object padlock = new object();
private ThreadSingleton()
{
}
public static ThreadSingleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new ThreadSingleton();
}
}
return instance;
}
}
}