Chapter 4. Singleton Pattern


In This Chapter

object Instantiation 66

Singleton Versus Static Members 69

Building a Simple Singleton 69

Building a Settings Framework 71

Summary 74

The Singleton design pattern is used to limit a class to one instance and provide global access to that instance. In many cases, you need to limit a class to only one instance. Common examples include classes that manage resources that are intrinsically singular such as selection focus, navigation history, and window depth. Consider the case of a class that manages the state of the user's cursor. Because there is only ever one cursor, you shouldn't have more than one instance of that class. Another example is a class that loads application settings from an XML file and provides access to those settings. You wouldn't want to waste resources by having two instances of that class or by loading the XML file more than once.

The dilemma in such cases is how to ensure that only one instance of a class exists and how to make that one instance globally accessible. The Singleton design pattern is a time-tested solution to this problem.

Essentially, three features make up a 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. This is usually achieved by making the constructor private. However, ActionScript 3.0 doesn't have private constructors. Later in this chapter, we'll examine an alternative way of restricting instantiation in ActionScript 3.0.




Advanced ActionScript 3 with Design Patterns
Advanced ActionScript 3 with Design Patterns
ISBN: 0321426568
EAN: 2147483647
Year: 2004
Pages: 132

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net