package Src { /** * Written by Leezhm, 10th February, 2009 * Contact : Leezhm@126.com * * An example of singleton class **/ public class CSingleton { // variable private static var _instance = new CSingleton(); protected function CSingleton() { } public static function getInstance():CSingleton { if (undefined != CSingleton._instance) { return CSingleton._instance; } else { throw Error("Could not create the instace!"); } } } }
Rebuild會出現1153:A constructor can only be declared public.錯誤,錯誤原因在錯誤描述語句描述的很清楚,也就是Constructor在Actionscript中只能聲明為public。而我當時寫的時候,犯了習慣性的錯誤,因為我學習的C++和C#中寫singleton pattern總是將constructor聲明為protected或者private,所以也就"理所當然"地這樣寫了(還是應該好好重視每種編程語言的基礎,雖然都是標準的OO語言,但應該還是各有自己的特色的,不然也就沒吸引力了)。既然這樣,我們就無法保證用戶不用new來創建singleton class對象了,在我思考中,同QQ群上一位網友討論了哈,他給我推薦了一種解決方案,如下:
復制代碼 代碼如下:
Public function CSingleton() { Throw Error("error!"); }
但后來通過自己的測試,發現這樣是不行的,Actionscript的異常機制貌似跟C#和C++不同,其實還是創建了對象,即使拋出了Exception(當然我沒有很深入的測試,也許結果并不正確,但這里我要推薦另一種在Actionscript中實現singleton pattern的方法)。后來自己在網上找到一本好書《Advanced Actionscript 3 with Design Pattern》,在它的Part III中的Chapter 4中找到了關于Actionscript中singleton的討論。
/** * Written by Leezhm, 14th February, 2009 * Contact : Leezhm@126.com * * An example of singleton class **/
public class CSingleton { // variable private static var _instance = new CSingleton(new SingletonEnforcer());
public function CSingleton(enforcer:SingletonEnforcer) { }
public static function getInstance():CSingleton { if (undefined != CSingleton._instance) { return CSingleton._instance; } else { throw Error("Could not create the instace!"); } }