U3D框架—单例框架

写程序应遵循的原则:高内聚(内容的聚合),低耦合(功能与功能之间的联系)

代码里尽量不要有冗余:既重复,没有用的代码

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

/// 
/// 单例框架,使用泛型,限制条件:T被实例
/// where T:new() 表示T这个类型要实例
/// 
/// 
public class SingleTon 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
{
    public AudioManager() { }
    public float currentAud;
}

public class Demo
{
    public Demo()
    {
        AudioManager.GetInstance().currentAud = 1f;
    }
}

/// 
/// 简单的单例
/// 
public class SimpleSingleTon
{
    //惰性实例化:既调用的时候再实例化
    private static SimpleSingleTon instance;
    public static SimpleSingleTon GetInstance()
    {
        if (instance == null)
        {
            instance = new SimpleSingleTon();
            return instance;
        }
        return instance;
    }
    private SimpleSingleTon() { }
}

  

你可能感兴趣的:(U3D框架—单例框架)