ActionScript 3.0 Design Patterns

(Chris Devlin) #1

114 | Chapter 3: Singleton Pattern


Save the file asAlert.as. As you can see, this Singleton design pattern doesn’t have to


be saved as “Singleton,” and the only reason that name was used in the previous


examples was to help you better see its structure, and where it belonged in the appli-


cation. In fact, it’s almost identical to the otherSingleton.asfiles used as examples in


this chapter, and even has the same methods as in Example 3-8. However, this exam-


ple includes a property used as a variable in the font color of the text field used here.


Conceivably, your application may need different colored messages to differentiate


categories of advisements your application might employ.


In ActionScript 3.0, you can create aTextFieldinstance in one of two ways. First,


you can create it dynamically in the script, as we will do in this example. Alterna-


tively, you can create a MovieClip object on the stage, embed aTextFieldin the


movie clip, and then reference the embeddedTextField. Unless you have a good rea-


son for doing so, it’s more practical and uses less memory to just write the script for


theTextField. (Further on in this chapter, a movie clip in the shape of a shopping


cart with an embedded text field shows how to create and dynamically use a


TextField object on the stage.)


Open a new ActionScript file and after entering the code in Example 3-11, name the


fileAlertText.as and save it in the same folder asAlert.as.


{

Alert._instance=new Alert(new PrivateClass( ));
trace("Alert instantiated");
}
return Alert._instance;
}
//Alert Property
public var colorFont:uint;
//Alert Methods
public function getMsg( ):String
{
return _msg;
}
public function setMsg(alert:String):void
{
_msg = alert;
}
}
}


class PrivateClass
{
public function PrivateClass( ) {
trace("PrivateClass called");
}
}


Example 3-10. Alert.as

Free download pdf