先声明一个静态私有变量,如:instance;再声明一个静态公共方法,如:GetInstance,在该方法中判断instance为null时,通过GameObject.FindObjectOfType(typeof(MyClass))创建instance的实例(在C#中直接new一个新的实例),不为null则直接返回。
参考代码:
public class MyClass
{
private static MyClass instance;
public static MyClass GetInstance()
{
if (!instance)
{
instance = GameObject.FindObjectOfType(typeof(MyClass));
}
return instance;
}
}
线程安全一:
public class Singleton {
private static Singleton instance;
private Singleton (){
}
public static Singleton getInstance(){ //对获取实例的方法进行同步
if (instance == null){
synchronized(Singleton.class){
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
private static Singleton instance;
private Singleton (){
}
public static Singleton getInstance(){ //对获取实例的方法进行同步
if (instance == null){
synchronized(Singleton.class){
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
线程安全二:
public sealed class Singleton
{
private static volatile Singleton instance;
private static readonly object syncRoot = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
lock (syncRoot)
{
if (instance == null)
{
instance = new Singleton();
}
}
return instance;
}
}
}
{
private static volatile Singleton instance;
private static readonly object syncRoot = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
lock (syncRoot)
{
if (instance == null)
{
instance = new Singleton();
}
}
return instance;
}
}
}
线程安全三——双重锁:
public sealed class Singleton
{
private static volatile Singleton instance;
private static readonly object syncRoot = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
{
private static volatile Singleton instance;
private static readonly object syncRoot = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}