| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- using System;
- using System.Collections.Generic;
- namespace Model
- {
- public class ObjectPool
- {
- private static ObjectPool instance;
- public static ObjectPool Instance
- {
- get
- {
- return instance ?? (instance = new ObjectPool());
- }
- }
- private readonly Dictionary<Type, EQueue<Disposer>> dictionary = new Dictionary<Type, EQueue<Disposer>>();
- private ObjectPool()
- {
- }
- public static void Close()
- {
- instance = null;
- }
- private Disposer Fetch(Type type)
- {
- EQueue<Disposer> queue;
- if (!this.dictionary.TryGetValue(type, out queue))
- {
- queue = new EQueue<Disposer>();
- this.dictionary.Add(type, queue);
- }
- Disposer obj;
- if (queue.Count > 0)
- {
- obj = queue.Dequeue();
- obj.Id = IdGenerater.GenerateId();
- return obj;
- }
- obj = (Disposer)Activator.CreateInstance(type);
- return obj;
- }
- public T Fetch<T>() where T: Disposer
- {
- T t = (T) this.Fetch(typeof(T));
- t.IsFromPool = true;
- return t;
- }
-
- public void Recycle(Disposer obj)
- {
- Type type = obj.GetType();
- EQueue<Disposer> queue;
- if (!this.dictionary.TryGetValue(type, out queue))
- {
- queue = new EQueue<Disposer>();
- this.dictionary.Add(type, queue);
- }
- queue.Enqueue(obj);
- }
- }
- }
|