1. 程式人生 > >簡易的單例模式與物件池

簡易的單例模式與物件池

這是我第一次寫部落格,博主經驗尚淺,還請老鐵不吝賜教。

【1.萬能單例模式】

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//單例的報錯
public class SingletonException : System.Exception{
    public SingletonException(string msg) : base(msg){}
}

//萬能單例模式
public abstract class Singleton<T> where T : class,new()
{
    private static T instance = null;
    public static T Instance{
        get{
            if(instance == null)
                instance = new T();
            return instance;
        }
    }

    protected Singleton(){
        if(instance!=null)
            throw new SingletonException("This "+typeof(T).ToString()+" Singleton is not null!");
        Init();
    }

    protected abstract void Init();
}


【2.簡易的物件池】

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

public class PoolManager : Singleton<PoolManager>{
    private static GameObject Parent;
    public Dictionary<string, List<GameObject>> Pool;

    protected override void Init(){
        Pool = new Dictionary<string, List<GameObject>>();
        Parent = new GameObject();
        Parent.name = "Pool";
        Parent.SetActive(false);
        GameObject.DontDestroyOnLoad(Parent);
    }

    public void Push(GameObject obj){
        if(obj.transform.parent == Parent.transform)
            return;
        if(!Pool.ContainsKey(obj.name))
            Pool.Add(obj.name, new List<GameObject>());
        obj.transform.SetParent(Parent.transform);
        Pool[obj.name].Add(obj);
        obj.SetActive(false);
    }

    public GameObject Pop(string name, string path = null){
        if(string.IsNullOrEmpty(path)&&!path.Contains("/"))
            path += "/";
        GameObject result = null;
        if(!Pool.ContainsKey(name) || Pool[name].Count == 0){
            if(path==null){
                Debug.LogError("Obj Pool doesn't hava:" + name);
                return null;
            }
            result = Resources.Load(path + name) as GameObject;
            if(result==null)
                Debug.LogError("Cannot find  resource : " + path + name);
            result.name = name;
        }else
        {
            var resultList = from obj in Pool[name] where !obj.activeSelf select obj;
            result = resultList.First();
            if(result.transform.parent!= Parent.transform){
                Debug.LogError("obj not in Pool : " + result.name);
            }
        }
        return result;
    }
}


閒暇時間寫的,沒有來的及用在專案上,, 如果有錯誤請評論或者私信我,我會及時更改,謝謝大家的 支援!