ActionScript 3.0 Design Patterns

(Chris Devlin) #1

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


As you can see in Example 1-9, the setter method allows only the four expressions


we had listed for a dog. Anything else (including “Meow”) is not allowed. Next,


Example 1-10 shows how to interface with the encapsulated dog object:


EnterTestEncapSetin the Document class of the FLA file and test it. As you will see,


the string “Howl” is perfectly acceptable. Now, test it again using “Meow.” This


time, you will see that the object rejected the kitty cat sound as “Not dog talk.” This


arrangement represents the best of both worlds; encapsulation and a way to execute


operations within an encapsulated object.


The get and set methods


Another way to maintain encapsulation and hide the information in your objects is


to use the ActionScript 3.0getandsetmethods. Some programmers find it awk-


ward to create their own getter and setter methods as we did in the previous section,


preferring the simplicity of thegetaccessor andsetmutator.


Accessors and mutators versus Frankenstein: they sound like some-
thing from a horror flick, but the termsaccessorandmutatorare used
to describe getters and setters. The accessor (getter) does access orget
information, and that’s perfectly reasonable. But mutators? Well, if we
think about it, a mutation does refer to a change, and when we set
information, we do indeed change it. It too makes perfect sense. So if
you’re happily reading an article on design patterns and you see the
termsaccessor ormutator, don’t let it creep you out.

In looking at how get and set are used, a key feature is the absence of parentheses.


Changes (setting) are not accomplished by adding values. Rather, the getters and


setters are treated like properties where values are assigned or retrieved through


assignment.


Example 1-10. TestEncapSet.as


package
{
import flash.display.Sprite;


public class TestEncapSet extends Sprite
{
private var encapSet:EncapSet
public function TestEncapSet( )
{
encapSet=new EncapSet( );
encapSet.setDogTalk("Howl");
encapSet.showDogTalk( );
addChild(encapSet);
}
}
}

Free download pdf