如何将一个对象池用于多个对象

时间:2014-02-19 01:56:22

标签: actionscript-3 flash-builder flash-cs5

这是我在网上找到并使用的一个例子(我是对象池的新手)。它适用于单个对象类型,但不允许我创建不同对象的池

包 {     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;
    }
}

}

1 个答案:

答案 0 :(得分:1)

以下是没有对象计数限制的对象池示例。

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);
        }
     }

}