實現AS3的Singleton的兩種方法
- 作者:柳大·Poechant
- 郵箱:zhongchao.ustc#gmail.com (# -> @)
- 部落格:blog.csdn.net/poechant
- 日期:April 8th, 2012
1 建構函式隨機參數
利用隨機數,當做建構函式的參數,實現建構函式無法隨意調用。
package { class Singleton { private static var _instance:Singleton = null; // secret known only to this class private static const secret:Number = Math.random(); /** * @private */ public function Singleton(enforcer:Number) { if (enforcer != secret) { throw new Error("Error: use Singleton.instance instead"); } } /** * Global single instance */ public static function get instance():Singleton { if (_instance == null) { _instance = new Singleton(secret); } return _instance; } }}
2 私人類
在 AS3 檔案內部的包定義外部實現一個類,這個類就是檔案內私人的。
package{ class Singleton { private static var _instance:Singleton = null; public function Singleton(enforcer:PrivateClass) { } public function getInstance():Singleton { if (_instance == null) { _instance = new Singleton(); } return _instance; } }}class PrivateClass { public PrivateClass() { }}
-
轉載請註明來自柳大的CSDN部落格:blog.csdn.net/poechant
-