< Day Day Up > |
Now that we've seen how to implement Avatar as a MovieClip subclass, let's consider an alternative using object composition. This time, the Avatar class does not inherit from MovieClip . Instead, it creates an instance of AvatarSymbol and stores it in an instance property, av_mc . (Well, technically, the ActionScript object representation of that instance is stored in av_mc , but here is an example in which making a distinction between the symbol instance and the ActionScript object would make the discussion awkward , albeit more technically accurate. My editor tells me to "Avoid precision where it merely sacrifices clarity." So I will here and elsewhere in this book.) Example 13-2 shows a revised version of the Avatar class. This version defines a constructor because, now that Avatar is no longer a subclass of MovieClip , instances are instantiated with new . The AvatarSymbol clip instance is created in the Avatar constructor, which replaces the createAvatar( ) method. Because initialization is usually performed in a class's constructor function, we put some of the code from init( ) in the constructor and move the rest to a new method, setPosition( ) . Example 13-2. The composition-based Avatar classclass Avatar { public static var HAPPY:Number = 0; public static var SAD:Number = 1; public static var IDLE:Number = 2; private var av_mc:MovieClip; public function Avatar (name:String, target:MovieClip, depth:Number, x:Number, y:Number) { av_mc = target.attachMovie("AvatarSymbol", name, depth); setState(Avatar.HAPPY); setPosition(x, y); } public function setState(newState:Number):Void { switch (newState) { case Avatar.HAPPY: av_mc.gotoAndStop("HAPPY"); break; case Avatar.SAD: av_mc.gotoAndStop("SAD"); break; case Avatar.IDLE: av_mc.gotoAndStop("IDLE"); break; } } public function setPosition (x:Number, y:Number):Void { av_mc._x = x; av_mc._y = y; } } In many ways, the composition version of the Avatar class is cleaner and more flexible than its MovieClip subclass counterpart ”cleaner because it uses fewer methods and a traditional constructor, more flexible because it can easily change the av_mc to some other movie clip symbol if required. However, the MovieClip subclass version would still be preferable in the following situations:
|
< Day Day Up > |