Singleton Pattern Example Flash/AS3 (based on MVC)
Singleton Pattern makes MVC even better
Hello all,
the Singleton Pattern helps you to store persistent data in your application, which should be globally accessible at any time. Therefore it is recommended to use a Singleton Class for your Model in a MVC-Application. For example your Singleton Class could hold the data of a loaded XML-File or in a game it could hold the score/bodycount of the player. The Singleton Pattern makes sure you can access that data whenever and whereever you want with a simple statement like this: _model = Singleton.getInstance();
The function getInstance() just returns always the same instance, which is just created once at the first function call.
I just updated the popular Flash/Actionscript Basic Model View Controller example. For the Model I use the Singleton Design Pattern, which makes it very easy to access data throughout the entire application.
You can see I just call Singleton.getInstance(); to access the Model with all its data.
check out the new AS3 example here: MVC Singleton Slideshow. you can view the actionscript source via right-click on the Flash Slideshow. alternatively feel free to download the entire flash builder project here.
I recommend this basic setup for tiny Flash applications, which will help you to keep your code structured and clean. For bigger Actionscript applications you should think about using a mvc framework - for example Robotlegs.
Cheers,
Flo