to be more complete how i would actually program it is like this :

import mx.utils.Delegate;

class CombinationHandler
{
    // Declare the values used for each state
    static var STATE_A:Number = 1; //  1 << 0
    static var STATE_B:Number = 2; //  1 << 1
    static var STATE_C:Number = 4; //  1 << 2
    static var STATE_D:Number = 8; //  1 << 3

    // Either declare the combinations here, or just use
    // the STATE_A | STATE_B form in the declare handlers function
    static var COMBINATION_AB:Number = STATE_A | STATE_B;
    static var COMBINATION_BC:Number = STATE_B | STATE_C;
        
    // array of functions to handle particular states
    // and state combinations
    private var handlers:Array;
        
    public function CombinationHandler()
    {
        handlers = new Array();
        createHandlers();
    }
        
    private function createHandlers()
    {
        // single case handlers
        handlers[STATE_A] = Delegate.create(this,handleAOnly);
        handlers[STATE_B] = Delegate.create(this,handleBOnly);
        handlers[STATE_C] = Delegate.create(this,handleCOnly);
        handlers[STATE_D] = Delegate.create(this,handleDOnly);
                
        // combination handlers
        handlers[COMBINATION_AB] = Delegate.create(this,ABhandler);
        // OR
        // handlers[STATE_A | STATE_B] = ...
                
    }
        
    public function handleUpdate(a:Object,b:Object,c:Object,d:Object)
    {
        // 'Digitise' the state from the selected flag in a,b,c,d.
        var state:Number = (a.selected) | (b.selected << 1) |
                           (c.selected << 2) | (d.selected << 3);
                
        // call the function
        handlers[state]();
    }
}

I think this way adding and modifying handlers is easy and safe, youre not editing code thats surrounded by support code (like case:, else if etc) so its clear where each response to a particular state is configured. You can leave the declaration of the combinations out of the static declarations at the top of the class like i said and just create the combinations when defining the handler. That way when you add a combination its just one place to edit, not two, but you may have a case for using that information again so the static var could be useful. I dont know :)

btw, in all the places you see | (bitwise OR) you can use + because it works out the same, im just used to using the bitwise operators for dealing with bit-based states and state masks. Similary for the shifts (<<) you can change them for their equivalent multiplication.

thanks,

Martin

_______________________________________________
Flashcoders mailing list
Flashcoders@chattyfig.figleaf.com
http://chattyfig.figleaf.com/mailman/listinfo/flashcoders

Reply via email to