02.C语言和设计模式(访问者模式)
2014-06-25 09:17
253 查看
原文地址:http://blog.csdn.net/feixiaoxing/article/details/7188574
不知不觉当中,我们就到了最后一种设计模式,即访问者模式。访问者模式,听上去复杂一些。但是,这种模式用简单的一句话说,就是不同的人对不同的事物有不同的感觉。比如说吧,豆腐可以做成麻辣豆腐,也可以做成臭豆腐。可是,不同的地方的人未必都喜欢这两种豆腐。四川的朋友可能更喜欢辣豆腐,江浙的人就可能对臭豆腐更喜欢一些。那么,这种情况应该怎么用设计模式表达呢?
[cpp] view
plaincopy
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的时候就要做不同的判断了。
[cpp] view
plaincopy
void eat(struct _Visitor* pVisitor, struct _Tofu* pTofu)
{
assert(NULL != pVisitor && NULL != pTofu);
pVisitor->process(pTofu, pVisitor);
}
既然eat的操作最后还是靠不同的visitor来处理了,那么下面就该定义process函数了。
[cpp] view
plaincopy
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");
}
不知不觉当中,我们就到了最后一种设计模式,即访问者模式。访问者模式,听上去复杂一些。但是,这种模式用简单的一句话说,就是不同的人对不同的事物有不同的感觉。比如说吧,豆腐可以做成麻辣豆腐,也可以做成臭豆腐。可是,不同的地方的人未必都喜欢这两种豆腐。四川的朋友可能更喜欢辣豆腐,江浙的人就可能对臭豆腐更喜欢一些。那么,这种情况应该怎么用设计模式表达呢?
[cpp] view
plaincopy
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的时候就要做不同的判断了。
[cpp] view
plaincopy
void eat(struct _Visitor* pVisitor, struct _Tofu* pTofu)
{
assert(NULL != pVisitor && NULL != pTofu);
pVisitor->process(pTofu, pVisitor);
}
既然eat的操作最后还是靠不同的visitor来处理了,那么下面就该定义process函数了。
[cpp] view
plaincopy
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");
}
相关文章推荐
- C语言和设计模式(访问者模式) 【文章都是来自网络,只要自己吸取了就是自己的】
- C语言和设计模式(访问者模式)
- 15、C语言和设计模式(访问者模式)
- C语言设计模式:责任链、观察者和访问者
- C语言和设计模式(之单件模式)02
- C语言 设计模式之访问者模式
- C语言和设计模式(访问者模式)
- C语言和设计模式(访问者模式) 24
- 乐在其中设计模式(C#) - 访问者模式(Visitor Pattern)
- 访问者设计模式
- 设计模式--访问者设计模式
- 设计模式笔记(24)---访问者模式(行为型)
- 设计模式笔记(24)---访问者模式(行为型)
- 设计模式--访问者模式(Visitor)
- 设计模式学习02-观察者模式
- [导入]C#面向对象设计模式纵横谈(24):(行为型模式) Visitor 访问者模式.zip(10.41 MB)
- 设计模式笔记 23. Visitor 访问者模式(行为型模式)
- 设计模式之访问者模式(Visitor)
- 设计模式(3)-访问者模式 Vistor Pattern
- 设计模式--访问者模式(Visitor)