Friday, December 28, 2012

Lazy Initialization

package 
{
    import flash.display.Sprite;
    import flash.events.Event;
    /**
     * ...
     * @author JMIM
     */
    public class Main extends Sprite 
    {
        public var lazyObject:LazyInitClass;
        public var myArrayContainer:Object = { object: null };
        private var counter:int = 0;
        
        public function Main():void 
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }
        
        private function init(e:Event = null):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            // entry point
            
            lazyObject = new LazyInitClass( myArrayContainer );
            this.addEventListener(Event.ENTER_FRAME, update);
        }
        
        
        public function update(e:Event):void
        {
            lazyObject.update();
            counter++;
            if (counter == 100)
            {
                myArrayContainer.object = ["1", "2", "3"];
            }
        }

    }
}

internal class LazyInitClass
{
    //if this works, make different kinds of lazy init containers for all the different data types.
    public var _initialized:Boolean = false;
    public var theArray:Array = null;
    public var arrayContainer:Object;
    
    public function LazyInitClass( inArrayContainer:Object )
    {
        arrayContainer = inArrayContainer;
    }
    
    public function update():void
    {
        if (!_initialized)
        {
            trace("checking for non-null references");
            theArray = arrayContainer.object;
            if (theArray != null) { _initialized = true;}
        }
        else
        {
            trace("initialized!");
        }
    }
}

No comments:

Post a Comment