Flex, ActionScript and Related Stuffs

Enjoy!!!!

Singleton Pattern

Posted by flexrays 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()

4 Responses to “Singleton Pattern”

  1. 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. 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. flexrays said

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

  4. 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

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>