C語言 設計模式之訪問者模式
更新時間:2017年01月28日 09:15:26 投稿:lqh
這篇文章主要介紹了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函數(shù)了。
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++ 題解LeetCode2360圖中的最長環(huán)示例
這篇文章主要為大家介紹了C C++ 題解LeetCode2360圖中的最長環(huán)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10
深入理解數(shù)組指針與指針數(shù)組的區(qū)別
本篇文章是對數(shù)組指針與指針數(shù)組的區(qū)別進行了詳細的分析介紹,需要的朋友參考下2013-05-05
C++11新特性中auto 和 decltype 區(qū)別和聯(lián)系
這篇文章主要介紹了C++11新特性中auto 和 decltype 區(qū)別和聯(lián)系的相關資料,需要的朋友可以參考下2017-01-01

