123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- using System;
- using System.Collections.Generic;
- namespace KYFramework
- {
- public class ComponentQueue : Component
- {
- public string TypeName { get; }
- private readonly Queue<Component> queue = new Queue<Component>();
- public ComponentQueue(string typeName)
- {
- this.TypeName = typeName;
- }
- public void Enqueue(Component component)
- {
- component.Parent = this;
- this.queue.Enqueue(component);
- }
- public Component Dequeue()
- {
- return this.queue.Dequeue();
- }
- public Component Peek()
- {
- return this.queue.Peek();
- }
- public int Count
- {
- get
- {
- return this.queue.Count;
- }
- }
- public override void Dispose()
- {
- if (this.IsDisposed)
- {
- return;
- }
- base.Dispose();
- while (this.queue.Count > 0)
- {
- Component component = this.queue.Dequeue();
- component.IsFromPool = false;
- component.Dispose();
- }
- }
- }
- public class ObjectPool : Component
- {
- private readonly Dictionary<Type, Queue<object>> pool = new Dictionary<Type, Queue<object>>();
-
- public T Fetch<T>() where T: class
- {
- return this.Fetch(typeof (T)) as T;
- }
- public object Fetch(Type type)
- {
- Queue<object> queue = null;
- if (!pool.TryGetValue(type, out queue))
- {
- return Activator.CreateInstance(type);
- }
- if (queue.Count == 0)
- {
- return Activator.CreateInstance(type);
- }
- return queue.Dequeue();
- }
- public void Recycle(object obj)
- {
- Type type = obj.GetType();
- Queue<object> queue = null;
- if (!pool.TryGetValue(type, out queue))
- {
- queue = new Queue<object>();
- pool.Add(type, queue);
- }
- // 一种对象最大为1000个
- if (queue.Count > 1000)
- {
- return;
- }
- queue.Enqueue(obj);
- }
- }
- }
|