// // Pool.h // // This code is derived from Universal Tween Engine // Licensed under Apache License 2.0 - http://www.apache.org/licenses/LICENSE-2.0 // /** * A light pool of objects that can be resused to avoid allocation. * Based on Nathan Sweet pool implementation */ #ifndef __Pool__ #define __Pool__ #include #include namespace TweenEngine { template class PoolCallback { public: virtual void onPool(T *obj) = 0; virtual void onUnPool(T *obj) = 0; }; template class Pool { private: std::vector objects; PoolCallback *callback; protected: virtual ~Pool() {} virtual T *create()=0; public: Pool(int initCapacity, PoolCallback *callback); T *get(); void free(T *obj); void clear(); int size(); void ensureCapacity(int minCapacity); }; // Implementation template Pool::Pool(int initCapacity, PoolCallback *cb) : objects(initCapacity), callback(cb) { } template T *Pool::get() { T *obj = nullptr; if (objects.empty()) { obj = create(); } else { obj = objects.back(); objects.pop_back(); if (obj == nullptr) obj = create(); } if (callback != nullptr) callback->onUnPool(obj); return obj; } template void Pool::free(T *obj) { if (obj == nullptr) return; bool contains = (std::find(objects.begin(), objects.end(), obj) != objects.end()); if (!contains) { if (callback != nullptr) callback->onPool(obj); objects.push_back(obj); } } template void Pool::clear() { objects.clear(); } template int Pool::size() { return objects.size(); } template void Pool::ensureCapacity(int minCapacity) { objects.reserve(minCapacity); } } #endif /* defined(__Pool__) */