复习二(单例模式)

单例模式(Singleton Pattern)

是最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

注意:
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。

C#版本的 Singleton 类。

    public class Singleton
    {
        //创建 Singleton的一个对象
        private static Singleton instance = new Singleton();

        //获取唯一可用的对象
        public static Singleton GetInstance()
        {
            return instance;
        }

        //让构造函数为 private,这样该类就不会被其他类实例化
        private Singleton() { }

        public void showMessage()
        {
            print("Hello World!");
        }
    }

使用方式

Singleton.GetInstance().showMessage();

Unity版本的Singleton类。

public class Singleton : MonoBehaviour
{

    //私有的静态实例
    private static Singleton_instance = null;
    //共有的唯一的,全局访问点
    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {    //查找场景中是否已经存在单例
                _instance = GameObject.FindObjectOfType<Singleton>();
                if (_instance == null)
                {    //创建游戏对象然后绑定单例脚本
                    GameObject go = new GameObject("Singleton");
                    _instance = go.AddComponent<Singleton>();
                }
            }
            return _instance;
        }
    }

    private void Awake()
    {    //防止存在多个单例
        if (_instance == null)
            _instance = this;
        else
            Destroy(gameObject);
    }

    public void showMessage()
    {
        print("Hello World!");
    }
}
使用方式
 Singleton.Instance.showMessage();

泛型单例模板

class Singleton<T> where T : class, new()
    {
        private static T _instance;
        private static readonly object syslock = new object();

        public static T getInstance()
        {
            if (_instance == null)
            {
                lock (syslock)
                {
                    if (_instance == null)
                    {
                        _instance = new T();
                    }
                }
            }
            return _instance;
        }
    }

使用方式

 class myclass : Singleton<myclass>
    {
        public void showMessage()
        {
            Console.WriteLine("Hello World");
        }
    }
    myclass.getInstance().showMessage();


猜你喜欢

转载自blog.csdn.net/qq_41996509/article/details/80824195