سؤال

This is an example of one I found online and used (I'm new to object pooling). It works for a single object type but won't allow me to create a pool of different objects

package { import starling.display.DisplayObject;

public class SpritePool
{
    private var pool:Array;
    private var counter:int;

    public function SpritePool(type:Class, len:int)
    {
        pool = new Array();
        counter = len;

        var i:int = len;
        while(--i > -1)
            pool[i] = new type();
    }

    public function getSprite():DisplayObject
    {
        if(counter > 0)
            return pool[--counter];
        else
            throw new Error("You exhausted the pool!");
    }

    public function returnSprite(s:DisplayObject):void
    {
        pool[counter++] = s;
    }
}

}

هل كانت مفيدة؟

المحلول

Here is an example of object pool without object count limit.

import flash.utils.Dictionary;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;

public class ObjectPool {

    public function ObjectPool()
    {
        throw new Error("don't create instance");
    }

    private static const objectDict:Dictionary = new Dictionary();

    public static function getObject(c:Class):Object{

        //if you want add a object count limit,try to check the count here
        if (objectDict[c] == null) {
            objectDict[c] = [];
        }

        var t:Array = objectDict[c] as Array;

        if (t.length > 0) {
            return t.shift();
        } else {
            return new c();
        }
    }

    public static function putObject(obj:Object):void {

        var c:Class = Class(getDefinitionByName(getQualifiedClassName(obj)));

        if (objectDict[c] == null) {
            return;
        }

        var t:Array = objectDict[c] as Array;

        if (t && t.indexOf(obj) == -1) {
            t.push(obj);
        }
     }

}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top