Singleton Pattern
Posted by Almost Noted on June 20, 2007
One of the design patterns in the Object-Oriented-Programming languages like ActionScript 3.0.
The Singleton design pattern is used to limit a class to one instance and provide global access to that instance
Common examples include classes that manage resources that are intrinsically singular such as
1. Selection focus
2. Navigation history
3. Window depth
4. Class that manages the state of user’s cursor
5. Class that loads application setting from an XML file and provide access to those settings
Essential features of Singleton class
• A private static property that holds the single instance of the class
• A public static method that provides access to the single instance if it’s created and creates the single instance if it hasn’t been created yet
• A way of restricting access to instantiating the class
Example – Creating a Singleton
package
{
public class MyClass
{
private static var _instance:MyClass
public function MyClass(enforcer:SingletonEnforcer)
{
}
public static function getInstance():MyClass
{
if(MyClass._instance == null)
{
MyClass._instance = new MyClass(new SingletonEnforcer());
}
}
}
}
class SingletonEnforcer {}
Invoking a Singleton inside another class
MyClass.getInstance()
Claude Needham said
I can not get this class to build.
The error I receive is:
A file found in a source-path can not have more than one externally visible definition.
What am I overlooking?
flexrays said
Hi ,, Can you please put the class outside the package definition please.. I think i have confused a bit by putting the class inside the package definition..
package
{
public class MyClass
{
}
}
class SingletonEnforcer {}
flexrays said
I have changed the post accordingly.. Sorry for the inconvenience.. Please let me know if this solves your problem? Thanks
Girish said
Hi
Can you check the following post [regarding singleton class] in forum and reply me asap.
http://www.flexdeveloper.eu/forums/index.php/topic,477.new.html
Brian said
Good post. Obviously the last post was’nt replied to asap, haha (@Girish 2007), how cheeky of him to ask:)
Atish Singh said
this is helpful and good post
!!