10.12.2012 Views

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Example 1-6. TestNoEncap.as<br />

package<br />

{<br />

import flash.display.Sprite;<br />

}<br />

public class TestNoEncap extends Sprite<br />

{<br />

public var noEncap:NoEncap;<br />

public function TestNoEncap( )<br />

{<br />

noEncap=new NoEncap( );<br />

noEncap.dogTalk="Meow";<br />

noEncap.showDogTalk( );<br />

addChild(noEncap);<br />

}<br />

}<br />

Open a new Flash document file, and, in the Document class window, type in<br />

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

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

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

multiply that by every un-encapsulated class you use, you can imagine the mess you<br />

might have. So let’s find a fix for this.<br />

Private variables<br />

The easiest way to insure encapsulation is to use private variables. The private statement<br />

in <strong>ActionScript</strong> <strong>3.0</strong>, whether it’s used with variables, constants or methods<br />

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

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

also excludes subclasses. (This is a difference from <strong>ActionScript</strong> 2.0; so watch out for<br />

it if you’re converting an application from <strong>ActionScript</strong> 2.0 to <strong>ActionScript</strong> <strong>3.0</strong>.)<br />

To see how the private statement will change how the application works,<br />

Example 1-7 changes the NoEncap class by adding the private statement to the<br />

variables.<br />

Example 1-7. Encap.as<br />

package<br />

{<br />

//This is GOOD OOP -- It has encapsulation<br />

import flash.text.TextField;<br />

import flash.display.Sprite;<br />

public class Encap extends Sprite<br />

{<br />

private var dogTalk:String="Woof, woof!";<br />

private var textFld:TextField=new TextField( );<br />

Encapsulation | 17

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!