A construct I often use when the list of "things to make a decision on" gets too big to be practical in an if/else or switch statement is to make a table with values and callbacks. For example, something like this (C):

struct keymap {
    int key;
    int (*callback)(struct data *data);

    int end;
};

...

struct keymap controls[] = {
    {'a', move_left},
    {'d', move_right},
    ...
    {.end = 1}
};

...

struct keymap *
keymap_find(int key)
{
    for(struct keymap *selmap = controls; !selmap->end; selmap++)
        if(selmap->key == key)
            return selmap;

    return NULL;
}

...

int
some_exec_function(struct data *data)
{
    struct keymap *selmap = keymap_find(get_key());

    if(selmap == NULL)
        return 0;

    return selmap->callback(data);
}

I have studied more "design patterns" than I care to admit, and have found nothing that quite captures this type of design. I know the paradigm in particular is somewhat declarative, because in the end, the controls are defined by the table, so you are saying "what to do" instead of "how to do it", and thus adding new entries and understanding intent are extremely straightforward and easy.

I have no clue what the proper terminology is, and I would like to study it for similar designs, so that I can improve my approach in the long run.

有帮助吗?

解决方案

It appears you are building a table of values and address of the routine to call. This appears to be a "Dispatch Table".

许可以下: CC-BY-SA归因
scroll top