Actionscript 3.0中Singleton實現 修正篇_Flash as3

來源:互聯網
上載者:User
在前面的blog中,代碼如下:
複製代碼 代碼如下:

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的討論。

由於我們沒法把constructor聲明為private,那就可以給constructor傳遞一個private的variable,同樣可以達到不能new的目的。但是怎麼樣才能讓一個只對singleton class有private範圍的variable呢,我們要注意Actionscript的一些規則,比如在一個AS檔案中只能有一個Package,一個和AS檔案同名的Main Class。但我們在AS檔案的包外聲明一個class,而且這樣聲明的class只對package中的class有範圍,對包外是不可見的。所以可以如下來寫這個Singleton class:
複製代碼 代碼如下:

package Src
{

/**
* 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!");
}
}

}
}

class SingletonEnforcer {}

BTW: 順便附上一張電子書中關於Actionscript 3中Singleton Pattern Class講解的照片,如下:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.