ActionScript 3.0 Design Patterns

(Chris Devlin) #1

16 | Chapter 1: Object-Oriented Programming, Design Patterns, and ActionScript 3.0


Hiding Your Data from Bad Consequences


To see why you might want to encapsulate your data, we’ll take a look at two pro-


grams. One is not encapsulated, leading to unwanted consequences, and the other is


encapsulated, preventing strange results.


If you make a dog object, you may want to include an operation that includes the


way a dog communicates. For purposes of illustration, we’ll include a method called


dogTalkthat will let the dog make different sounds. The dog’s communication will


include the following:



  • Woof

  • Whine

  • Howl

  • Grrrr


We’ll start off withbadOOP to illustrate how you may end up with something you


don’t want in your dog’s vocabulary. Example 1-5 is not encapsulated and will


potentially embarrass your dog object.


As a black box, youshould notbe able to change the internal workings of a class, but


this class is wide open, as you will see. You can interact with an encapsulated object


through its interface, but you should not allow an implementation to make any


changes it wants. Example 1-6 breaks into the object and changes it in ways you


don’t want.


Example 1-5. NoEncap.as


package
{
//This is BAD OOP -- No encapsulation
import flash.text.TextField;
import flash.display.Sprite;


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


public function NoEncap( )
{
addChild(textFld);
textFld.x=100;
textFld.y=100;
}
function showDogTalk( )
{
textFld.text=dogTalk;
}
}
}

Free download pdf