DesignPattern_AbstractFactory
摘录自:设计模式与游戏完美开发
工程GitHub
SINGLETON—俺有6个漂亮的老婆,她们的老公都是我,我就是我们家里的老公Singleton,她们只要说道“老公”,都是指的同一个人,那就是我(刚才做了个梦啦,哪有这么好的事)
单例模式:单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例单例模式。单例模式只应在有真正的“单一实例”的需求时才可使用。
using UnityEngine;
using System.Collections;
namespace DesignPattern_Singleton
{
// 单例模式
public class Singleton
{
public string Name {get; set;}
private static Singleton _instance;
public static Singleton Instance
{
get
{
if (_instance == null)
{
Debug.Log("产生Singleton");
_instance = new Singleton();
}
return _instance;
}
}
private Singleton(){}
}
}
using UnityEngine;
using System.Collections;
using DesignPattern_Singleton;
public class SingletonTest : MonoBehaviour {
// Use this for initialization
void Start () {
UnitTest();
UnitTest_ClassWithCounter();
}
// 单例模式测试方法
void UnitTest ()
{
Singleton.Instance.Name = "Hello";
Singleton.Instance.Name = "World";
Debug.Log (Singleton.Instance.Name);
//Singleton TempSingleton = new Singleton();// 錯誤 error CS0122: `DesignPattern_Singleton.Singleton.Singleton()' is inaccessible due to its protection level
}
// 有计数功能类別的测试方法
void UnitTest_ClassWithCounter ()
{
// 有计数功能的类別
ClassWithCounter pObj1 = new ClassWithCounter();
pObj1.Operator();
ClassWithCounter pObj2 = new ClassWithCounter();
pObj2.Operator();
pObj1.Operator();
}
}
-
一种是具有计数功能的类,来达到单例的效果
using UnityEngine;
using System.Collections;
// 有計數功能的類別
public class ClassWithCounter
{
protected static int m_ObjCounter = 0;
protected bool m_bEnable=false;
public ClassWithCounter()
{
m_ObjCounter++;
m_bEnable = ( m_ObjCounter ==1 )? true:false ;
if( m_bEnable==false)
Debug.LogError("目前物件數["+m_ObjCounter+"]超過1個!!");
}
public void Operator()
{
if( m_bEnable ==false)
return ;
Debug.Log ("可以執行");
}
}
-
还有一种比较安全的单例写法
public class Singleton
{
public const string Name = "Singleton";
static Singleton() { }
protected Singleton() { }
protected static volatile Singleton m_instance = null;
protected readonly object m_syncRoot = new object();
protected static readonly object m_staticSyncRoot = new object();
public static Singleton Instance
{
get
{
if (m_instance == null)
{
lock (m_staticSyncRoot)
{
if (m_instance == null) m_instance = new Singleton();
}
}
return m_instance;
}
//set { m_instance = value; }
}
}
Unity版
public class Singleton
{
public const string Name = "Singleton";
static Singleton() { }
protected Singleton() { }
protected static volatile Singleton m_instance = null;
protected readonly object m_syncRoot = new object();
protected static readonly object m_staticSyncRoot = new object();
public static Singleton Instance
{
get
{
if (m_instance == null)
{
lock (m_staticSyncRoot)
{
if (m_instance == null)
{
GameObject Obj = new GameObject("Singleton ", typeof(Singleton ));
instance = Obj.GetComponent<Singleton >();
}
}
}
return m_instance;
}
//set { m_instance = value; }
}
}
网友评论