c#单例模式基类

在unity3d中:

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

public abstract class MonoSingleton<T> : MonoBehaviour
    where T : MonoBehaviour
{
    private static T m_instance;

    public static T Instance
    {
        get
        {
            return m_instance;
        }
    }

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

}


在普通类中:

  1. class Singleton<T> where T: class,new()  
  2. {  
  3.     private static T _instance;  
  4.     private static readonly object syslock=new object();  
  5.   
  6.     public static T getInstance()   
  7.     {  
  8.         if (_instance == null)  
  9.         {  
  10.             lock (syslock) {  
  11.                 if (_instance == null)  
  12.                 {  
  13.                     _instance = new T();  
  14.                 }  
  15.             }  
  16.         }  
  17.        return _instance;  
  18.     }  
  19. }  

猜你喜欢

转载自blog.csdn.net/qq_36927190/article/details/79471073