为Actionscript实现singleton类

RKC*_*KCY 1 apache-flex singleton design-patterns actionscript-3

我知道actionscript在任何时候都不允许私有contstructor但是如果我想在动作脚本中编写一个sinlgleton类那么如何在actionscript中实现它.

任何人都可以在动作脚本中提供单例模式的示例吗?

rei*_*den 8

我使用这样的东西:

package singletons
{

    [Bindable]
    public class MySingleton
    {
        private static var _instance:MySingleton;

        public function MySingleton(e:Enforcer)  {
            if(e == null) {
                throw new Error("Hey!  You can't do that!  Call getInstance() instead!");
            }   
        }

        public static function getInstance():MySingleton {
            if(_instance == null) {
                _instance = new MySingleton (new Enforcer);
            }
            return _instance;
        }
    }
}

// an empty, private class, used to prevent outside sources from instantiating this locator
// directly, without using the getInstance() function....
class Enforcer{}
Run Code Online (Sandbox Code Playgroud)