ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Encapsulation | 17

Open a new Flash document file, and, in the Document class window, type in


TestNoEncap. When you test the file, you’ll see “Meow” appear on the screen. Such a


response from your dog object is all wrong. Dogs don’t meow and cats don’t bark.


However, that’s what can happen when you don’t encapsulate your class. When you


multiply that by every un-encapsulated class you use, you can imagine the mess you


might have. So let’s find a fix for this.


Private variables


The easiest way to insure encapsulation is to use private variables. Theprivatestate-


ment in ActionScript 3.0, whether it’s used with variables, constants or methods


(functions) makes sure that only the class that defines or declares it can use it. This


not only shuts out implementations that attempt to assign any value they want, but it


also excludes subclasses. (This is a difference from ActionScript 2.0; so watch out for


it if you’re converting an application from ActionScript 2.0 to ActionScript 3.0.)


To see how the private statement will change how the application works,


Example 1-7 changes the NoEncapclass by adding theprivate statement to the


variables.


Example 1-6. TestNoEncap.as


package
{
import flash.display.Sprite;


public class TestNoEncap extends Sprite
{
public var noEncap:NoEncap;
public function TestNoEncap( )
{
noEncap=new NoEncap( );
noEncap.dogTalk="Meow";
noEncap.showDogTalk( );
addChild(noEncap);
}
}
}


Example 1-7. Encap.as


package
{
//This is GOOD OOP -- It has encapsulation
import flash.text.TextField;
import flash.display.Sprite;


public class Encap extends Sprite
{
private var dogTalk:String="Woof, woof!";
private var textFld:TextField=new TextField( );

Free download pdf