123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164 |
- using System;
- using System.Collections.Generic;
- namespace Fort23.Core
- {
- public class ComponentQueue : CObject
- {
- public string TypeName { get; }
- private readonly Queue<CObject> _queue = new Queue<CObject>();
- public ComponentQueue(string typeName)
- {
- this.TypeName = typeName;
- }
- public async void Enqueue(CObject entity)
- {
- if (entity == null)
- {
- return;
- }
- if (!entity.isActive)
- {
- return;
- }
- await entity.AwaitTask();
- if (!entity.isActive)
- {
- return;
- }
- entity.isActive = false;
- this._queue.Enqueue(entity);
- entity.DormancyObj();
- }
- public CObject Dequeue()
- {
- return this._queue.Dequeue();
- }
- public CObject Peek()
- {
- return this._queue.Peek();
- }
- public Queue<CObject> Queue => this._queue;
- public int Count => this._queue.Count;
- public override void Dispose()
- {
- while (this._queue.Count > 0)
- {
- CObject component = this._queue.Dequeue();
- component.Dispose();
- }
- }
- public override void ActiveObj()
- {
- }
- public override void DormancyObj()
- {
- }
- }
- public class CObjectPool : CObject
- {
- private static CObjectPool _instance;
- public static CObjectPool Instance
- {
- get
- {
- if (_instance == null)
- {
- _instance = new CObjectPool();
- }
- return _instance;
- }
- }
- private readonly Dictionary<Type, ComponentQueue> _dictionary = new Dictionary<Type, ComponentQueue>();
- public CObject Fetch(Type type)
- {
- CObject obj;
- if (!this._dictionary.TryGetValue(type, out ComponentQueue queue))
- {
- obj = (CObject)Activator.CreateInstance(type);
- }
- else if (queue.Count == 0)
- {
- obj = (CObject)Activator.CreateInstance(type);
- }
- else
- {
- obj = queue.Dequeue();
- }
- obj.isActive = true;
- obj.ActiveObj();
- return obj;
- }
- public T Fetch<T>() where T : CObject
- {
- T t = (T)this.Fetch(typeof(T));
- return t;
- }
- public void Recycle(CObject obj)
- {
- if (obj == null)
- {
- return;
- }
- Type type = obj.GetType();
- ComponentQueue queue;
- if (!this._dictionary.TryGetValue(type, out queue))
- {
- queue = new ComponentQueue(type.Name);
- this._dictionary.Add(type, queue);
- }
- queue.Enqueue(obj);
- }
- public void Clear()
- {
- foreach (KeyValuePair<Type, ComponentQueue> kv in this._dictionary)
- {
- kv.Value.Dispose();
- }
- this._dictionary.Clear();
- }
- public override void Dispose()
- {
- foreach (KeyValuePair<Type, ComponentQueue> kv in this._dictionary)
- {
- kv.Value.Dispose();
- }
- this._dictionary.Clear();
- _instance = null;
- }
- public override void ActiveObj()
- {
- }
- public override void DormancyObj()
- {
- }
- }
- }
|