The visitor pattern for the C language design pattern

  • 2020-05-12 02:58:34
  • OfStack

The C language visitor pattern

Summary:

The visitor pattern, sounds a little more complicated. However, in a simple sentence, this pattern means that different people have different feelings about different things. For example, tofu can be made into spicy tofu or stinky tofu. However, people in different places may not all like these two kinds of tofu. Sichuan friends may prefer spicy tofu, jiangsu and zhejiang people may prefer stinky tofu. So, how can this situation be expressed in design patterns?


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; 

That's it. When you make eat, you have to make a different judgment.


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

Now that the eat operation is finally handled by a different visitor, it is time to define the process 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");   
} 

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: