設計模式看的有些不懂,也不知理解對不對,千里之行,始於鍵盤下,於是寫個代碼感受一下。
網上有些中介者的例子,有個舉得是公司內各部門間的例子,感覺闡釋的挺好,在我理解看來,倘若有10種對象,他們都有一個變量叫‘庫存’,於是可能每個對象都要維護這個庫存變量,而且這個變量的改變會影響其他對象,那麼可不可以把這個變量拿出來單獨放在一個地方,也許此時可以考錄把它放在中介者裏,感覺有點像全局變量,現實中這個中介者或許有些像服務中心,或者有人說是中介,這個中介者不但能放變量,還可以提供服務。
寫了個就餐的小程序,差強人意吧。
裏面包含顧客,廚師,和服務員,服務員是顧客和廚師的中介者,顧客一來就獅子大開口說要吃一噸魚,而廚師做不了這麼多魚,所以由服務員來調停。
#include <stdio.h>
#include <stdlib.h>
struct Customer {
struct Waiter* waiter;
int ( *request) (struct Customer* customer, int fish);
};
struct Cooker {
struct Waiter* waiter;
void ( *cook)(struct Cooker* cooker, int fish);
};
struct Waiter { //中介者waiter負責提供數據供雙方訪問,類似於全局變量
int fish;
struct Customer* customer; //當customer指向waiter後,就可以通過訪問waiter中的結構體來訪問其他對象
struct Cooker* cooker;
int ( *wrequest)(struct Customer* customer, int fish); //customer
};
void cook (struct Cooker* cooker, int fish) {
cooker->waiter->fish = fish;
}
int request (struct Customer* customer, int fish) {
return customer->waiter->wrequest(customer, fish); //調用終結者中的函數 ,使維護集中在中介者中
}
int wrequest (struct Customer* customer, int fish) { //很多資源和函數都集中在中介者中,
if (fish > customer->waiter->fish) {
printf ("抱歉,廚師反饋沒有 %d 那麼多魚了,重新點菜吧。\n", fish);
return -1;
}
else {
printf ("點菜成功,廚房還有很多魚,足夠你們吃了\n");
return 0;
}
}
int fish(void) {
return rand()%50 +40;
}
int main (void) {
srand((unsigned) time(0));
struct Customer customer;
struct Cooker cooker;
struct Waiter waiter;
waiter.wrequest = wrequest;
cooker.waiter = &waiter;
customer.waiter = &waiter;
cooker.cook = cook;
customer.request = request;
cooker.cook (&cooker, 50); //廚師今天只能做50條魚
while (customer.request (&customer, fish())); //消費者跟服務員waiter說要個N條大魚
}
return customer->waiter->wrequest(customer, fish); //調用終結者中的函數 ,使維護集中在中介者中
}
這是消費者的請求函數,說是要吃多少魚,請求時調用中介者,真正的函數實現是在中介這種,於是核心的數據和方法會集中到中介者中,也許就把分散在不同類中的東西集中到了一起,從維護多個類或對象,到把重點放在中介者上也許就簡單了吧。