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");
}
感激閱讀,希望能協助到大家,謝謝大家對本站的支持!