using System; using System.Collections.Generic; namespace IFramework { /// /// 基础对象池 /// /// public abstract class ObjectPool : Unit, IDisposable, IObjectPool { /// /// 数据容器 /// protected Queue pool { get { return _lazy.Value; } } private Lazy> _lazy = new Lazy>(() => { return new Queue(); }, true); /// /// 自旋锁 /// protected object para = new object(); /// /// 存储数据类型 /// public virtual Type type { get { return typeof(T); } } /// /// 池子数量 /// public int count { get { return pool.Count; } } /// /// 释放时 /// protected override void OnDispose() { Clear(null); } /// /// 获取 /// /// /// public virtual T Get(IEventArgs arg = null) { lock (para) { T t; if (pool.Count > 0) { t = pool.Dequeue(); } else { t = CreateNew(arg); OnCreate(t, arg); } OnGet(t, arg); return t; } } /// /// 回收 /// /// /// public void Set(object obj, IEventArgs args) { if (obj is T) { Set((T)obj, args); } } /// /// 回收 /// /// /// /// public virtual bool Set(T t, IEventArgs arg = null) { lock (para) { if (!pool.Contains(t)) { if (OnSet(t, arg)) { pool.Enqueue(t); } return true; } else { Log.E("Set Err: Exist " + type); return false; } } } /// /// 清除 /// /// public void Clear(IEventArgs arg = null) { lock (para) { while (pool.Count > 0) { var t = pool.Dequeue(); OnClear(t, arg); IDisposable dispose = t as IDisposable; if (dispose != null) dispose.Dispose(); } } } /// /// 清除 /// /// /// public void Clear(int count, IEventArgs arg = null) { lock (para) { count = count > pool.Count ? 0 : pool.Count - count; while (pool.Count > count) { var t = pool.Dequeue(); OnClear(t, arg); } } } /// /// 创建一个新对象 /// /// /// protected abstract T CreateNew(IEventArgs arg); /// /// 数据被清除时 /// /// /// protected virtual void OnClear(T t, IEventArgs arg) { } /// /// 数据被回收时,返回true可以回收 /// /// /// /// protected virtual bool OnSet(T t, IEventArgs arg) { return true; } /// /// 数据被获取时 /// /// /// protected virtual void OnGet(T t, IEventArgs arg) { } /// /// 数据被创建时 /// /// /// protected virtual void OnCreate(T t, IEventArgs arg) { } } }