Mono单例
- 场景里挂载了,先找场景里有的
- DontDestroyOnLoad
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Singleton
{
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
protected static T m_instance = null;
public static T instance
{
get
{
if (m_instance == null)
{
string name = typeof(T).ToString();
GameObject gameEntryInstance = GameObject.Find(name); //单例的名字都唯一,防止场景里已经有了
if (gameEntryInstance == null)
{
gameEntryInstance = new GameObject(name);
DontDestroyOnLoad(gameEntryInstance);
}
if (gameEntryInstance != null)
{
m_instance = gameEntryInstance.GetComponent<T>();
}
if (m_instance == null)
{
m_instance = gameEntryInstance.AddComponent<T>();
}
}
return m_instance;
}
}
public void StartUp()
{
}
protected void OnApplicationQuit()
{
m_instance = null;
}
}
}
c#单例
在对泛型的约束中,最常使用的关键字有where 和 new。
其中where关键字是约束所使用的泛型,该泛型必须是where后面的类,或者继承自该类。
new()说明所使用的泛型,必须具有无参构造函数,这是为了能够正确的初始化对象
/// <summary>
/// C#单例模式
/// </summary>
public abstract class Singleton<T> where T : class,new()
{
private static T instance;
private static object syncRoot = new Object();
public static T Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new T();
}
}
return instance;
}
}
protected Singleton()
{
Init();
}
public virtual void Init() { }
}
Lua单例
local function __init(self)
assert(rawget(self._class_type, "Instance") == nil, self._class_type.__cname.." to create singleton twice!")
rawset(self._class_type, "Instance", self)
end
local function __delete(self)
rawset(self._class_type, "Instance", nil)
end
local function GetInstance(self)
if rawget(self, "Instance") == nil then
rawset(self, "Instance", self.New())
end
assert(self.Instance ~= nil)
return self.Instance
end
local ResourcesManager = BaseClass("ResourcesManager", Singleton)