dimanche 8 novembre 2015

Is it incorrect to create a large message-handler lookup table?

I have a queue that I'm pushing messages to. The messages have a unique integer ID. I basically have something that looks like this:

#-------------------------
#Message handlers
#-------------------------
def noOperation():
    print "Do nothing"

def msgHandler1():
    print "Handling message with ID = 1"

def msgHandler2():
    print "Handling message with ID = 2"

#-------------------------
#Message lookup table
#-------------------------
lookupTable = {
    0: noOperation,
    1: msgHandler1,
    2: msgHandler2
    #...etc...
}

#-------------------------
#Message processing
#-------------------------
while threadActive:
    message = buffer.get(block=True)
    if message:
        lookupTable[message.id]()

My question is: Is there a more efficient way to do this sort of thing? If I have a few dozen message types, then my lookup table is going to get pretty big. Maybe this isn't really a problem - I'm not sure...it just somehow feels wrong to be creating this big table that maps to dozens of message handler methods. Is this sort of thing a well known problem with a well-defined solution? Are there any patterns that touch on this?

Aucun commentaire:

Enregistrer un commentaire