C語言 設計模式之訪問者模式
更新時間:2017年01月28日 09:15:26 投稿:lqh
這篇文章主要介紹了C語言 設計模式之訪問者模式的相關資料,需要的朋友可以參考下
C語言訪問者模式
概要:
訪問者模式,聽上去復雜一些。但是,這種模式用簡單的一句話說,就是不同的人對不同的事物有不同的感覺。比如說吧,豆腐可以做成麻辣豆腐,也可以做成臭豆腐??墒牵煌牡胤降娜宋幢囟枷矚g這兩種豆腐。四川的朋友可能更喜歡辣豆腐,江浙的人就可能對臭豆腐更喜歡一些。那么,這種情況應該怎么用設計模式表達呢?
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"); }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
您可能感興趣的文章: