C语言访问者模式 C语言 设计模式之访问者模式

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C语言访问者模式 C语言 设计模式之访问者模式

  2021-03-24 我要评论
想了解C语言 设计模式之访问者模式的相关内容吗,在本文为您仔细讲解C语言访问者模式的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C语言访问者模式,C语言访问者模式实例代码,C语言访问者模式详解,下面大家一起来学习吧。

C语言访问者模式

概要:

访问者模式,听上去复杂一些。但是,这种模式用简单的一句话说,就是不同的人对不同的事物有不同的感觉。比如说吧,豆腐可以做成麻辣豆腐,也可以做成臭豆腐。可是,不同的地方的人未必都喜欢这两种豆腐。四川的朋友可能更喜欢辣豆腐,江浙的人就可能对臭豆腐更喜欢一些。那么,这种情况应该怎么用设计模式表达呢?

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; 

    就是这样一个豆腐,eat的时候就要做不同的判断了。

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

    既然eat的操作最后还是靠不同的visitor来处理了,那么下面就该定义process函数了。

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");   
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们