单例模式

来源:互联网 发布:java面试选择题及答案 编辑:程序博客网 时间:2024/06/09 18:37

单例模式
保证一个类只有一个实例,并提供一个访问他的全局访问点。通常我们可以让一个全局变量使得一个对象被访问,但他不能防止你实例化多个对象。一个最好的办法就是,让类自身负责保存他的唯一实例。这个类可以保证没有其他实例被创建,并且他可以提供了一个访问该实例的方法。

class Singleton    {        private static Singleton instance;        private Singleton() { }        public static Singleton GetInstance()        {            if (instance == null)            {                instance = new Singleton();            }            return instance;        }    }    class Program    {        static void Main(string[] args)        {            Singleton s1 = Singleton.GetInstance();            Singleton s2 = Singleton.GetInstance();            if (s1 == s2)            {                Console.WriteLine("equal");            }            Console.ReadKey();        }}

单例模式因为Singleton类封装了他的唯一实例,这样可以严格控制客户应该怎样访问以及何时访问。简单地说就是对唯一实例的受控访问。
多线程单例的版本,lock是确保当一个线程位于代码的临界区时,另一个线程不进入临界区,如果其他线程试图进入锁定代码,则会一直等待,直到该对象被释放

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;        }    }

Unity3d 中比较方便的使用方式

using UnityEngine;using System.Collections;public class SomeObjectCreat : MonoBehaviour{    public GameObject root; //当前场景root结点    public Camera camera;    public static SomeObjectCreat instance;    //当前游戏玩家的头像    public UILabel Time_Label;//时间标签    public UILabel gemNum_Label;//获取宝石数目标签    public UILabel tipMessage;//游戏结束获得宝石数目文本提示    public GameObject gameOverTipMessage;//游戏结束信息弹出框    public UISprite playerHead;    private GameObject prefab;    private GameObject PlayerMolde;    public UnityEngine.Sprite[] left;    public UnityEngine.Sprite[] right;    public UI2DSpriteAnimation animation1;    public UI2DSpriteAnimation animation2;    void Start()    {        NGUITools.SetActive(gameOverTipMessage.gameObject, false);        Player player = GameManager.Instance().GetCurrentRollPlayer();        CharacterIf ci = player.characterInfo;        playerHead.atlas = ci.atlas;        playerHead.spriteName = ci.featureSmile;        playerHead.MakePixelPerfect();        playerHead.width /= 2;        playerHead.height /= 2;        //重复执行函数 第一个参数为函数名称,第二个为函数开始调用时间,第三个为函数调用时间间隔        InvokeRepeating("CountDown", 0, 1);    }    void Awake()    {        instance = this;        left = new UnityEngine.Sprite[10];        right = new UnityEngine.Sprite[10];        Player player = GameManager.Instance().GetCurrentRollPlayer();        prefab = Resources.Load<GameObject>("Prefabs/MiniGame/GetGem/财神" + player.name);        if (prefab == null)            prefab = Resources.Load<GameObject>("Prefabs/MiniGame/GetGem/财神小宝");        PlayerMolde = NGUITools.AddChild(root, prefab);        PlayerMolde.transform.localPosition = prefab.transform.localPosition;        animation1 = PlayerMolde.GetComponent<UI2DSpriteAnimation>();        if (player.name == "梅老板")        {            PlayerMolde.GetComponent<UI2DSprite>().width = 300;            PlayerMolde.GetComponent<UI2DSprite>().height = 300;        }        for (int i = 0; i < 10; i++)        {            right[i] = animation1.frames[i];        }        for (int j = 0; j < 10; j++)        {            left[j] = animation1.frames[j + 10];        }    }}
0 0