C language and design patterns (visitor pattern)

Understand a word

Mainly deal with some specified scene environment, after a visit and things to you, based on that person's characteristics, to give back. (If the characteristic changes frequently, the design pattern is not suitable)

premise

Unconsciously, we went to the final design model, that visitor pattern. Visitor pattern, it sounds complicated. However, this model is a simple words, that different people have different feelings about different things. For instance, right, tofu can be made spicy tofu, tofu can also be made. However, the different places of people who do not like these two tofu. Sichuan friends may prefer spicy tofu, Jiangsu and Zhejiang people may prefer to tofu few. So, this situation should be how to use design patterns to express it?

example

typedef struct _Tofu
{
    int type;
    void (*eat)	(struct _Visitor* pVisitor, struct _Tofu* pTofu);
}Tofu;
 
typedef struct _Visitor
{
    int region;
    void (*process)(struct _Tofu* pTofu, struct _Visitor* pVisitor);
}Visitor;

Is such a tofu, eat when you do a different judgment

  void eat(struct _Visitor* pVisitor, struct _Tofu* pTofu)
{
    assert(NULL != pVisitor && NULL != pTofu);
 
    pVisitor->process(pTofu, pVisitor);
}

Since the operation finally eat by different visitor to deal with, then the following process in relation to the definition of the function.

void process(struct _Tofu* pTofu, struct _Visitor* pVisitor)
{
    assert(NULL != pTofu && NULL != pVisitor);
 
    if(pTofu->type == SPICY_FOOD && pVisitor->region == WEST ||
        pTofu->type == STRONG_SMELL_FOOD && pVisitor->region == EAST)
    {
        printf("I like this food!\n");
        return;
    }
 
    printf("I hate this food!\n");   
}

to sum up

Design pattern often say is: find and change package. Whether to adopt the visitor pattern, depends on "change" is. Visitor pattern, the "change" is the specific visitors, followed by the object structure; however, if a particular element will change, you must not use the visitor pattern, because it "affect the situation as a whole", the late maintenance on the bad.

Published 261 original articles · won praise 6 · views 8105

Guess you like

Origin blog.csdn.net/qq_23929673/article/details/103538419