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會出現(xiàn)1153:A constructor can only be declared public.錯誤,錯誤原因在錯誤描述語句描述的很清楚,也就是Constructor在Actionscript中只能聲明為public。而我當(dāng)時寫的時候,犯了習(xí)慣性的錯誤,因為我學(xué)習(xí)的C++和C#中寫singleton pattern總是將constructor聲明為protected或者private,所以也就"理所當(dāng)然"地這樣寫了(還是應(yīng)該好好重視每種編程語言的基礎(chǔ),雖然都是標(biāo)準(zhǔn)的OO語言,但應(yīng)該還是各有自己的特色的,不然也就沒吸引力了)。既然這樣,我們就無法保證用戶不用new來創(chuàng)建singleton class對象了,在我思考中,同QQ群上一位網(wǎng)友討論了哈,他給我推薦了一種解決方案,如下:
復(fù)制代碼 代碼如下:
Public function CSingleton() { Throw Error("error!"); }
但后來通過自己的測試,發(fā)現(xiàn)這樣是不行的,Actionscript的異常機制貌似跟C#和C++不同,其實還是創(chuàng)建了對象,即使拋出了Exception(當(dāng)然我沒有很深入的測試,也許結(jié)果并不正確,但這里我要推薦另一種在Actionscript中實現(xiàn)singleton pattern的方法)。后來自己在網(wǎng)上找到一本好書《Advanced Actionscript 3 with Design Pattern》,在它的Part III中的Chapter 4中找到了關(guān)于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!"); } }