ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Example: Car Steering Adapter | 191

TheCarAdapterclass implements theICarinterface and has a parameterized con-


structor that receives aLegacyCarinstance. It contains four public methods as speci-


fied in the interface. All four methods use one of the public methods in theLegacyCar


class for implementation. The steering angle is set in discrete steps of 50 degrees, as


discussed previously. Note thenSteeringAngleproperty that keeps track of the cur-


rent steering angle of the car. Adapter classes can have their own properties and


methods to support implementation.


The Client


All that’s left to accomplish is to develop a client to test the adapter. The client


(Main.asshown in Example 5-12) creates a new instance ofLegacyCarand passes


two parameters to the constructor that places it on the center of the stage. Next, it


creates an instance of CarAdapterand passes the previously created LegacyCar


instance to it. The client also has to receive input from the keyboard to steer the car.


To do this, the client attaches theonKeyPress( )listener function to respond tokey


downevents. This listener function calls appropriate methods on the adapter class


based on keyboard input. TheonKeyPress( )listener function responds to the left,


public function CarAdapter(car:LegacyCar)
{
this.legacyCar = car;
this.nSteeringAngle = 0;
this.goStraight( );
}


public function start( ):void
{
legacyCar.start( );
}


public function turnMoreToTheLeft( ):void
{
legacyCar.setSteeringWheelAngle(nSteeringAngle -= 50);
}


public function turnMoreToTheRight( ):void
{
legacyCar.setSteeringWheelAngle(nSteeringAngle += 50);
}


public function goStraight( ):void
{
legacyCar.setSteeringWheelAngle(nSteeringAngle = 0);
}


}
}


Example 5-11. CarAdapter.as (continued)

Free download pdf