Here is class code:
package mmg; class SimpleCache<t> { public var instance(get, never):T; private var _targetClass:Class<t>; private var _currentIndex:Int; private var _instances:Array<t>; public function new(targetClass:Class<t>, initialCapacity:Int) { _targetClass = targetClass; // Base class of all of objects _currentIndex = initialCapacity - 1; // Index of current free object _instances = []; // Array of all instances // Fill it up for (i in 0...initialCapacity) { _instances[i] = getNewInstance(); } } private function getNewInstance():T { return Type.createEmptyInstance(_targetClass); } private function get():T { if (_currentIndex >= 0) { // Returning free object from cache _currentIndex--; return _instances[_currentIndex + 1]; } else { // If cache is empty we should create one more instance return getNewInstance(); } } private function put(instance:T):Void { _currentIndex++; // If cache is overfilled if (_currentIndex == _instances.length) { // We should put instance to the back of the instances array _instances[_instances.length] = instance; } else { // Putting instance to the free cell of array _instances[_currentIndex] = instance; } } }Usage example:
// init cache var cache:SimpleCache<ourobjectclass> = new SimpleCache(OurObjectClass, 50); // take on of instances var tmp:OurObjectClass = cache.instance; tmp.doSomething(); // put object back to cache cache.put(tmp);
No comments:
Post a Comment