單例模式(Singleton Pattern)
是最簡單的設(shè)計(jì)模式之一台猴。這種類型的設(shè)計(jì)模式屬于創(chuàng)建型模式虐骑,它提供了一種創(chuàng)建對(duì)象的最佳方式鲁驶。
這種模式涉及到一個(gè)單一的類鉴裹,該類負(fù)責(zé)創(chuàng)建自己的對(duì)象,同時(shí)確保只有單個(gè)對(duì)象被創(chuàng)建钥弯。這個(gè)類提供了一種訪問其唯一的對(duì)象的方式径荔,可以直接訪問,不需要實(shí)例化該類的對(duì)象脆霎。
注意:
1总处、單例類只能有一個(gè)實(shí)例。
2睛蛛、單例類必須自己創(chuàng)建自己的唯一實(shí)例鹦马。
3、單例類必須給所有其他對(duì)象提供這一實(shí)例忆肾。
C#版本的 Singleton 類荸频。
public class Singleton {
//創(chuàng)建 Singleton的一個(gè)對(duì)象
private static Singleton instance = new Singleton();
//獲取唯一可用的對(duì)象
public static Singleton GetInstance(){
return instance;
}
//讓構(gòu)造函數(shù)為 private,這樣該類就不會(huì)被其他類實(shí)例化
private Singleton(){}
public void showMessage(){
print("Hello World!");
}
}
使用方式
Singleton.GetInstance().showMessage();
Unity版本的Singleton類难菌。
public class Singleton: MonoBehaviour {
//私有的靜態(tài)實(shí)例
private static Singleton_instance = null;
//共有的唯一的试溯,全局訪問點(diǎn)
public static Singleton Instance
{
get
{
if (_instance == null)
{ //查找場(chǎng)景中是否已經(jīng)存在單例
_instance = GameObject.FindObjectOfType<Singleton>();
if (_instance == null)
{ //創(chuàng)建游戲?qū)ο笕缓蠼壎▎卫_本
GameObject go = new GameObject("Singleton");
_instance = go.AddComponent<Singleton>();
}
}
return _instance;
}
}
private void Awake()
{ //防止存在多個(gè)單例
if (_instance == null)
_instance = this;
else
Destroy(gameObject);
}
public void showMessage()
{
print("Hello World!");
}
}
使用方式
Singleton .Instance.showMessage();
泛型單例模板
class Singleton<T> where T: class,new()
{
private static T _instance;
private static readonly object syslock=new object();
public static T getInstance()
{
if (_instance == null)
{
lock (syslock) {
if (_instance == null)
{
_instance = new T();
}
}
}
return _instance;
}
}
使用方式
class myclass : Singleton<myclass> {
public void showMessage()
{
Console.WriteLine("Hello World");
}
}
myclass.getInstance().showMessage();