Singleton pattern in ActionScript 3
the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object.
This is useful when exactly one object is needed to coordinate actions across the system.
Useing of singleton in AS3 code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package { public class as3Singleton { public function as3Singleton(_e:Enforcer) { } /** * singleton static instance holder */ private static var instance:as3Singleton; /** * * @return as3Singleton Instance (Signleton) * */ public static function getInstance():as3Singleton { if (instance == null) instance = new as3Singleton(new Enforcer(), _stage); return instance; } } } class Enforcer{public function Enforcer(){}} |
Simple MVC in ActionScript 3
I always used to apply this pattern in most simple way.
Its help me to create few view states use same functionality.
First i create interfaces to Module, Controller and View state:
2
3
4
5
6
package {
flash.events.IEventDispatcher;
public interface IModule extends IEventDispatcher {
}
}
2
3
4
5
package {
public interface IController {
}
}
2
3
4
5
package {
public interface IView {
}
}
Than lets create the MVC:
2
3
4
5
6
7
8
9
package {
flash.events.EventDispatcher;
public class TestModule extends EventDispatcher implements IModule {
public function TestModule(){
}
}
}
2
3
4
5
6
7
8
9
10
package {
public class TestController implements IController {
private var testModule:IModule;
public function TestController(_module:IModule){
testModule = _module;
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
package {
import flash.display.Sprite;
public class TestView extends Sprite implements IView {
private var testModule:IModule;
private var testController:IController;
public function TestController(_controller:IController, _module:IModule){
testController = _controller;
testModule = _module;
}
}
}
Now lets connect them all:
2
3
4
5
6
7
8
9
10
11
12
13
14
package {
import flash.display.Sprite;
public class TestApp extends Sprite {
public function TestApp(){
var testModule:IModule = new TestModule();
var testController:IController = new TestControler(testModule);
var testView:IView = new TestView(testController, testModule);
addChild(testView as Sprite);
}
}
}