Wednesday, August 1, 2012

mx.core.Singleton

IMyInterface
package xxx
{
    public interface IMyInterface
    {
        function foo():void;
        function bar():void;
    }
}

MyClass
package xxx
{
    public class MyClass implements IMyInterface
    {
        private static var _instance:IMyInterface;
        /**
        * Must be implemented. Will be called from mx.core.Singleton;
        */
        public static function getInstance():IMyInterface
        {
            if (!_instance)
            {
                _instance = new MyClass();
            }
            return _instance;
        }

        public function foo():void
        {
            // Some code here
        }

        public function bar():void
        {
            // Some code here
        }

    }
}

Somewhere in a 'registration' module:
import mx.core.Singleton;
import xxx.IMyInterface;
import xxx.MyClass;


Singleton.registerClass(getQualifiedClassName(IMyInterface), Class(MyClass));

How to use:
import mx.core.Singleton;
import xxx.IMyInterface;

var myi:IMyInterface = Singleton.getInstance(getQualifiedClassName(IMyInterface)) as IMyInterface; 

myi.foo();
myi.bar();

No comments:

Post a Comment