在游戲開發(fā)中,最常用的設(shè)計(jì)模式化應(yīng)該是「單例模式」
比如說如迟,我們在做UI框架的時(shí)候,為了防止頁面重建殷勘,一把都會(huì)把界面設(shè)計(jì)成單例。
考慮到游戲中有大量的頁面需要做玲销,有什么方法,可以省掉我們每次頁面都需要編寫單例代碼嗎痒玩?
這就體現(xiàn)出面對對象的優(yōu)勢了
我們可以創(chuàng)建一個(gè)基類來實(shí)現(xiàn)單例模式,界面開發(fā)只需要繼承就好了
MonoBehavior單例
using UnityEngine;
using System.Collections;
public class test2 : MonoBehaviour {
public static test2 instance;
// Use this for initialization
void Awake () {
instance = this;
}
// Update is called once per frame
void Update () {
}
}
普通類的單例
using UnityEngine;
using System.Collections;
public class test2 {
private static test2 instance;
public static test2 Instance
{
get
{
if (null == instance)
instance = new test2();
return instance;
}
set { }
}
}
單例基類
public class Singleton<T> where T : new()
{
private static T s_singleton = default(T);
private static object s_objectLock = new object();
public static T singleton
{
get
{
if (Singleton<T>.s_singleton == null)
{
object obj;
Monitor.Enter(obj = Singleton<T>.s_objectLock);//加鎖防止多線程創(chuàng)建單例
try
{
if (Singleton<T>.s_singleton == null)
{
Singleton<T>.s_singleton = ((default(T) == null) ? Activator.CreateInstance<T>() : default(T));//創(chuàng)建單例的實(shí)例
}
}
finally
{
Monitor.Exit(obj);
}
}
return Singleton<T>.s_singleton;
}
}
protected Singleton()
{
}
}
感謝:@草帽領(lǐng)