文章目录声明:本文为个人笔记,用于学习研究使用非商用,内容为个人研究及综合整理所得,若有违规,请联系,违规必改。
- 前言
- 一、单例模式
- 二、实现
- 二、用途
- 三、优缺点
- 总结
前言
单例模式学习总结.下面代码中继承MonoBehaviour为Unity的脚本.非Unity开发无须在意.
一、单例模式
定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点
二、实现
- 常规单例
public class UIManager
{
//单例模式
private static UIManager instance;
public static UIManager Instance
{
get {
if (instance == null)
{
instance = new UIManager();
}
return instance;
}
- 泛型单例
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class Singletonwhere T : new() { static T instance; public static T Instance { get { if (instance == null) { instance = new T(); } return instance; } } }
- 加锁的普通单例
class Singleton
{
private static Singleton instance;
private static readonly object syncRoot = new object();
private Singleton()
{
}
public static Singleton GetInstance()
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
- 加锁的泛型单例
public class Singletonwhere T : new() { private static T s_singleton = default(T); private static object s_objectLock = new object(); public static T singleton { get { if (Singleton .s_singleton == null) { object obj; Monitor.Enter(obj = Singleton .s_objectLock);//加锁防止多线程创建单例 try { if (Singleton .s_singleton == null) { Singleton .s_singleton = ((default(T) == null) ? Activator.CreateInstance () : default(T));//创建单例的实例 } } finally { Monitor.Exit(obj); } } return Singleton .s_singleton; } } protected Singleton() { }
- 继承MONO的普通单例
sing UnityEngine;
using System.Collections;
public class test2 : MonoBehaviour {
public static test2 instance;
// Use this for initialization
void Awake () {
instance = this;
}
}
- 继承Mono的抽象单例
using UnityEngine; public abstract class MonoSingleton: MonoBehaviour where T : MonoBehaviour { public bool global = true; static T instance; public static T Instance { get { if (instance == null) { instance =(T)FindObjectOfType (); } return instance; } } void Start() { if (global) DontDestroyOnLoad(this.gameObject); this.OnStart(); } protected virtual void OnStart() { } }
二、用途
让类可以像静态类一样被全局访问,且保证只有一个实例.自己项目中常用于Manager及Service等管理及服务类中.
三、优缺点
-
优点:使用方便,灵活.
-
缺点: 除非被销毁了,不然实例创建后一直存在,无论是否使用.
总结
保持饥饿,保持愚蠢.
这世界唯一能够相信的就是你付出的努力和你走过的路.



