无聊,发一贴代码,对象池
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Cache with LRU
/// </summary>
/// <typeparam name="T"></typeparam>
public class MemoryCache<T> :IEnumerable{
protected class NodeInfo<T> {
public string key;
public T obj;
}
List<NodeInfo<T>> cacheQueue;
int cacheSize;
/// <summary>
/// Cache with LRU
/// </summary>
/// <param name="size">cache size</param>
public MemoryCache(int size){
cacheQueue = new List<NodeInfo<T>>();
cacheSize = size;
}
/// <summary>
/// reset cache size
/// </summary>
/// <param name="size"></param>
public void SetCacheSize(int size) {
cacheSize = size;
}
/// <summary>
/// try get obj from cache
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public T GetFromCache(string key) {
var cacheObj = cacheQueue.Find(n => {
return n.key == key;
});
if (cacheObj == null) {
return default(T);
}
else {
cacheQueue.Remove(cacheObj);
cacheQueue.Insert(0, cacheObj);
return cacheObj.obj;
}
}
/// <summary>
/// add or update cache
/// </summary>
/// <param name="key"></param>
/// <param name="obj"></param>
public void Put(string key,T obj) {
var cacheObj = cacheQueue.Find(n => {
return n.key == key;
});
if (cacheObj == null) {
var newNode = new NodeInfo<T>();
newNode.key = key;
newNode.obj = obj;
cacheQueue.Insert(0, newNode);
}
else {
cacheObj.obj = obj;
cacheQueue.Remove(cacheObj);
cacheQueue.Insert(0, cacheObj);
}
Clear(cacheSize);
}
/// <summary>
/// remove node by key
/// </summary>
/// <param name="key"></param>
public void Remove(string key) {
var cacheNode = cacheQueue.Find(n => {
return n.key == key;
});
if (cacheNode!=null) {
cacheQueue.Remove(cacheNode);
}
}
/// <summary>
/// loop remove item until less than hold num
/// </summary>
/// <param name="hold"></param>
public void Clear(int hold) {
if (hold<0) {
hold = 0;
}
while (cacheQueue.Count > hold) {
cacheQueue.RemoveAt(cacheQueue.Count - 1);
}
//Resources.UnloadUnusedAssets();
}
public int GetCacheSize() {
return cacheQueue.Count;
}
public void PrintAll() {
for (int i = cacheQueue.Count-1; i >= 0; i--) {
var node = cacheQueue[i];
Debug.Log(node.key+":"+node.obj);
}
}
public IEnumerator GetEnumerator() {
return new MCEnum(this.cacheQueue);
}
protected class MCEnum : IEnumerator {
List<NodeInfo<T>> cacheQueue;
public MCEnum(List<NodeInfo<T>> cacheQueue) {
this.cacheQueue = cacheQueue;
}
int iter = -1;
public object Current {
get {
if (iter < cacheQueue.Count && iter >= 0) {
return cacheQueue[iter].obj;
}
return null;
}
}
public bool MoveNext() {
iter++;
if (iter < cacheQueue.Count) {
return true;
}
return false;
}
public void Reset() {
iter = -1;
}
}
}