Call Us: +1-888-227-1645
AS3 tutorial on the Singleton pattern

AS3 Tutorial – The Singleton Pattern

Eric Meyer

2 min read

One of the most important patterns that we use over here is the Singleton. It’s used when you need to restrict use of a class to one or only one instance. This comes in handy when you are casting things like application wide settings, or if you are building something like a logging service. There is a bit of disagreement on the use of the singleton, but it really boils down to two questions:

If you answer yes to these two questions, you might have the case to build a singleton. – So here is how you go about doing it in AS3 -it’s a bit tricksy ’cause as3 has no private constructors:

Example Singleton
[as3]
package somepackage{
public class MySingleton{
private static var _instance:MySingleton;
public function MySingleton(enforcer:Enforcer){}
public static function getInstance():mySingleton{
if(MySingleton._instance==null){
MySingleton._instance = new MySingleton(new Enforcer)}
return MySingleton._instance
}

public function someExampleService():void{}

}

}
class Enforcer{}
[/as3]

So that’s the basic code structure. Some items of note is the inclusion of the empty Enforcer class outside of the package. This is critical, as you don’t want to place your Enforcer in the package or class definition of the singleton. So lets talk about how this thing works. The key is the conditional static function getInstance. It only creates the internal variable _instance if one does not already exist. In addition to this restriction, the Enforcer class will generate an error if you try to instantiate an instance of MySingleton using the new keyword. Try it…

Great…So how do you instantiate this pattern? Simple… just access the class methods through the getInstance() method:

MySingleton.getInstance().someExampleService()

Happy coding!

From the blog

Latest Articles

Let's build something amazing together

Give us a ring and let us know how we can help you reach your goals. Or if you'd like, start a chat. We're usually available 9-5 EST. We try to respond to every inquiry within one business day.

Phone number
+1-888-227-1645

Technologies and services we work with:

Laravel Laravel
WordPress WordPress
React ReactJS
EmberJS EmberJS
woocommerce WooCommerce
next.js NextJS
gatsby Gatsby
Shopify Shopify
VueJs VueJS
contentful Contentful
next.js JAMStack
gatsby Laravel Jigsaw
WPEngine WP Engine
Laravel Livewire Laravel Livewire
Netlify Netlify