Using design patterns
Design patterns help developers structure their application in a particular, established way. There
are many different design patterns that developers use in classes and for application design. Using
a design pattern is helpful when working in larger groups, because there is a defined set of
guidelines. Design patterns help ensure that every developer in the group can read a snippet of
code and understand what is happening. The guidelines keep the code layout, architecture,
placement, and style consistent throughout the project, regardless of who writes the code. Design
patterns might also make developing applications more efficient, because you can reuse the
ActionScript that you write in several different user interfaces.
A common use of class members is the Singleton design pattern. The Singleton design pattern
makes sure that a class has only one instance, and provides a way of globally accessing the
instance. For more information on the Singleton design pattern, see
www.macromedia.com/devnet/mx/coldfusion/articles/design_patterns.html.
Often there are situations when you need exactly one object of a particular type in a system. For
example, in a chess game there is only one chessboard, and in a country, there is only one capital
city. Even though there is only one object, it is attractive to encapsulate the functionality of this
object in a class. However, you might need to manage and access the one instance of that object.
Using a global variable is one way to do this, but global variables are often not desirable. A better
approach is to make the class manage the single instance of the object itself using class members,
such as the following:
class Singleton {
private var instance:Singleton = null;
public function doSomething():Void {
//...
}
public static function getInstance():Singleton {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
The Singleton object can then be accessed using
that the Singleton object is not created until it is actually needed—that is, until some other code
asks for it by calling the
can help code efficiency in many circumstances.
Note: Remember to not use too many classes for your application, because it can create many poorly
designed class files, which is not beneficial to the application's performance or your workflow.
104
Chapter 3: Using Best Practices
method. This is typically referred to as lazy creation, and
getInstance
Singleton.getInstance();
This also means
Need help?
Do you have a question about the FLASH MX 2004-USING ACTIONSCRIPT IN FLASH and is the answer not in the manual?
Questions and answers