ActionScript 3.0 Design Patterns

(Chris Devlin) #1

194 | Chapter 5: Adapter Pattern


interceptkey downevents, we need to attach listeners to interceptmouse downand


mouse moveevents. Note that the listeners should be attached to the stage rather


than theLegacyCarobject. This enables the listener functions to receive mouse clicks


over the broad area of the stage, as opposed to directly over the car object.


this.stage.addEventListener(MouseEvent.MOUSE_MOVE, this.doMouseMove);
this.stage.addEventListener(MouseEvent.MOUSE_DOWN, this.doMouseDown);

All that’s required now is to implement the listener functions that call the appropri-


ate methods in the adapter. ThedoMouseDown( )function listens tomouse downevents


and calls thegoStraight( ) method in the adapter.


private function doMouseDown(event:MouseEvent):void
{
this.carAdapter.goStraight( );
}

ThedoMouseMove( )function listens tomouse moveevents. It checks whether the


mouse has moved to the left or right from its last position. The last mouse position is


saved in theoldMouseStageXproperty. Based on whether the mouse moved to the left


or right, the adapter methodsturnMoreToTheLeft( )andturnMoreToTheRight( )are


called.


private function doMouseMove(event:MouseEvent):void
{
// change in horizontal mouse position
var xDiff = event.stageX - this.oldMouseStageX;
if (xDiff > 0) {
this.carAdapter.turnMoreToTheRight( );
} else {
this.carAdapter.turnMoreToTheLeft( );
}
event.updateAfterEvent( ); // process this event first
this.oldMouseStageX = event.stageX // save old mouse x position
}

As is evident from this example, that well-thought-out design of adapters can be used


in multiple contexts.


Example: List Display Adapter


Adapter patterns also come in handy to create reusable classes that use existing


classes to implement some of the required functionality. For example, think about


when you would want to display a list of values on theStage. There may be many


instances when you want to do this: lists of names, lists of high scores in a game, lists


of products in a shopping cart, etc. In Flash you can use aTextFieldto display a list,


putting each item on a separate line. However, this requires that the display text be


preformatted with a carriage return character ('\r', ASCII 13) separating each list


item before sending it out to theTextFieldobject for display. The following code


snippet will display a list using aTextField object.

Free download pdf