Flex, ActionScript and Related Stuffs

Enjoy!!!!

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()

6 Responses to “Singleton Pattern”

  1. Claude Needham's avatar

    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?

  2. Almost Noted's avatar

    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 {}

  3. Almost Noted's avatar

    flexrays said

    I have changed the post accordingly.. Sorry for the inconvenience.. Please let me know if this solves your problem? Thanks

  4. Girish's avatar

    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

  5. Brian's avatar

    Brian said

    Good post. Obviously the last post was’nt replied to asap, haha (@Girish 2007), how cheeky of him to ask:)

  6. Atish Singh's avatar

    Atish Singh said

    this is helpful and good post
    !!

Leave a reply to Girish Cancel reply

 
Design a site like this with WordPress.com
Get started