设计模式之单件模式【ActionScript3.0篇】
Singleton类代码:
1 package source
2 {
3 public class Singleton
4 {
5 // 声明Singleton的实例
6 private static var instance:Singleton;
7
8 public function Singleton()
9 {
10 // 构造函数
11 }
12
13 // 实例化Singleton类
14 public static function Instance():Singleton
15 {
16 if (instance == null)
17 {
18 instance = new Singleton();
19 }
20
21 return instance;
22 }
23
24 // 函数
25 public function ShowMsg(msg:String):String
26 {
27 return msg;
28 }
29 }
30 }
2 {
3 public class Singleton
4 {
5 // 声明Singleton的实例
6 private static var instance:Singleton;
7
8 public function Singleton()
9 {
10 // 构造函数
11 }
12
13 // 实例化Singleton类
14 public static function Instance():Singleton
15 {
16 if (instance == null)
17 {
18 instance = new Singleton();
19 }
20
21 return instance;
22 }
23
24 // 函数
25 public function ShowMsg(msg:String):String
26 {
27 return msg;
28 }
29 }
30 }
调用Singleton类代码:
1 import source.Singleton;
2
3 private function InitApp():void
4 {
5 var singleton:Singleton = Singleton.Instance();
6 var msg:String = singleton.ShowMsg("Hello world");
7 trace(msg);
8 }
2
3 private function InitApp():void
4 {
5 var singleton:Singleton = Singleton.Instance();
6 var msg:String = singleton.ShowMsg("Hello world");
7 trace(msg);
8 }