AS3 singleton implementations

后端 未结 1 2004
盖世英雄少女心
盖世英雄少女心 2020-12-19 11:08

I have seen so many implementations of singletons around, and i just want a singleton that

1.- instances on the first call 2.- instances only once (duh)

So

相关标签:
1条回答
  • 2020-12-19 11:26

    example 2 but with a twist since you should allow new Singleton() to be called at least once and I don't like instantiating things until I need them, thus the first call to instance() actually creates the instance... subsequent calls grab the original.

    EDIT: Sowed how it can also allow for if you call

    var singleton:Singleton = new Singleton();
    

    it will work... but all future tries will throw the error and force use of the getInstance() method

    public final class Singleton{
        private static var _instance:Singleton;
    
        public function Singleton(){
            if(_instance){
                throw new Error("Singleton... use getInstance()");
            } 
            _instance = this;
        }
    
        public static function getInstance():Singleton{
            if(!_instance){
                new Singleton();
            } 
            return _instance;
        }
    }
    
    0 讨论(0)
提交回复
热议问题