ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Minimalist Example of an MVC Pattern | 433

TheModel class extends theEventDispatcher class that already implements the


IEventDispatcher interface. Note the dispatchEvent( ) function call within the


setKey( )method. This sends aCHANGEevent to all registered observers when the


value oflastKeyPressed is changed within thesetKey( ) method.


Controller as a Concrete Strategy in a Strategy Pattern


The relationship between the controller and view is that of strategy and context in a


strategy pattern. Each controller will be a concrete strategy implementing a required


behavior defined in a strategy interface.


The controller


For our minimalist example, the behavior required of the controller is to handle a


key press event.IKeyboardInputHandleris the strategy interface (Example 12-3), and


defines a single method calledkeyPressHandler( ).


The concrete controller is theControllerclass (Example 12-4) that implements the


IKeyboardInputHandler interface.


private var lastKeyPressed:uint = 0;


public function setKey(key:uint):void
{
this.lastKeyPressed = key;
dispatchEvent(new Event(Event.CHANGE)); // dispatch event
}


public function getKey( ):uint
{
return lastKeyPressed;
}
}
}


Example 12-3. IKeyboardInputHandler.as


package
{
import flash.events.*;


public interface IKeyboardInputHandler
{
function keyPressHandler(event:KeyboardEvent):void
}
}


Example 12-2. Model.as (continued)

Free download pdf