设计模式之单例模式

前言:

首先介绍一下什么是单例,单例类和单例脚本

单例的标准形态:(也可以叫做单例类)

public class Singleton
{
       private static Singleton instance;
       
       public  static Singleton Instance
          {
                get{
                     if(null=instance)
                       {
                         instance=new Singleton();
                          
                        }
                        
                       return instance;


                    }
           }      
}

通用模板的单例类:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class SingletonClass<T> where T : new()
{
    //私有单例对象
    private static T instacne;


    public static T Instance
    {
        get
        {
            if (null == instacne)
            {
                instacne = new T();
            }
            return instacne;
        }
    }


}

那什么是单例脚本呢?其实就是继承了MonoBehaviour 的,能挂载在unity中运行的这么一个脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


/// <summary>
/// 单例脚本基类
/// </summary>
public class SingletonMono<T> : MonoBehaviour  where T : SingletonMono<T>
{
    private static T instance;


    public static T Instance
    {
        get
        {
            if (null == instance)
            {
                GameObject obj = new GameObject(typeof(T).Name);
                instance = obj.AddComponent<T>();
            }
            return instance;
        }
    }


    protected virtual void Awake()
    {
        instance = this as T;
    }


}

这是一个通用版的单例脚本,只要继承它的子类就可以通过里面的初始化,自动的实例出来使这个类成为单例脚本。

谨记:单例脚本千万不能挂载多次!可能会出现多种不同的bug

 正文:

        那么,什么是单例模式?

整个软件生命周期,某个类有且只能实例化一次,或者脚本只能运行一次;

比如说,对数据库连接和初始,各种管理类都需要使用单例,


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值