在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; } }
在普通类中:
- 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;
- }
- }