Singleton 執行器通過私有例項

在這種方法中,通過靜態方法訪問單個:

Singleton.getInstance();

要僅強制執行單例的一個例項,私有靜態變數將保留例項,而在建構函式中強制例項化例項的任何其他嘗試。

package {

public class Singleton {

    /** Singleton instance */
    private static var _instance: Singleton = new Singleton();

    /** Return singleton instance. */
    public static function getInstance():Singleton {
        return _instance;
    }

    /** Constructor as singleton enforcer. */
    public function Singleton() {
        if (_instance)
            throw new Error("Singleton is a singleton and can only be accessed through Singleton.getInstance()");
    }

}
}