写程序应遵循的原则:高内聚(内容的聚合),低耦合(功能与功能之间的联系)
代码里尽量不要有冗余:既重复,没有用的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 单例框架,使用泛型,限制条件:T被实例 /// where T:new() 表示T这个类型要实例 /// </summary> /// <typeparam name="T"></typeparam> public class SingleTon<T> where T:new(){ //声明单例,并赋默认值 private static T instance = default(T); public static T GetInstance() { if (instance == null) { instance = new T(); return instance; } return instance; } } public class AudioManager : SingleTon<AudioManager> { public AudioManager() { } public float currentAud; } public class Demo { public Demo() { AudioManager.GetInstance().currentAud = 1f; } } /// <summary> /// 简单的单例 /// </summary> public class SimpleSingleTon { //惰性实例化:既调用的时候再实例化 private static SimpleSingleTon instance; public static SimpleSingleTon GetInstance() { if (instance == null) { instance = new SimpleSingleTon(); return instance; } return instance; } private SimpleSingleTon() { } }