Last active
February 15, 2019 08:07
-
-
Save yangruihan/b2026726471df523425fa4eb981678c9 to your computer and use it in GitHub Desktop.
对象池
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Collections.Generic; | |
| /// <summary> | |
| /// 可入对象池接口 | |
| /// </summary> | |
| public interface IPoolable | |
| { | |
| void OnAwakeFromPool(); | |
| void OnReturnToPool(); | |
| } | |
| /// <summary> | |
| /// 对象池 | |
| /// </summary> | |
| /// <typeparam name="T"></typeparam> | |
| public class InstancePool<T> where T : IPoolable, new() | |
| { | |
| private readonly Stack<T> _instances; | |
| public InstancePool(int preSize = 0) | |
| { | |
| _instances = new Stack<T>(); | |
| for (var i = 0; i < preSize; i++) | |
| { | |
| var instance = default(T); | |
| _instances.Push(instance == null ? new T() : instance); | |
| } | |
| } | |
| public T Get() | |
| { | |
| T instance; | |
| if (IsEmpty()) | |
| { | |
| instance = default(T); | |
| instance = (instance == null) ? new T() : instance; | |
| } | |
| else | |
| { | |
| instance = _instances.Pop(); | |
| } | |
| instance.OnAwakeFromPool(); | |
| return instance; | |
| } | |
| public void Recycle(T instance) | |
| { | |
| if (_instances.Contains(instance)) | |
| { | |
| instance = default(T); | |
| } | |
| else | |
| { | |
| instance.OnReturnToPool(); | |
| _instances.Push(instance); | |
| } | |
| } | |
| private bool IsEmpty() | |
| { | |
| return _instances.Count == 0; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment