中介者模式: Define an object that encapsulates how a set of objects interact.Mediator promotes loose coupling by keeping objects from referring to each other explicitly,and it lets you vary their interaction independently.(用一个中介对象封装一系列的对象交互, 中介者使各对象不需要显示地相互作用, 从而使其耦合松散, 而且可以独立地改变它们之间的交互。 )
UML图:
代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 中介者接口
typedef struct {
void (*notify)(void*, char*);
} Mediator;
// 具体中介者类
typedef struct {
Mediator mediator;
char* name;
} ConcreteMediator;
void ConcreteMediator_notify(void* obj, char* message) {
ConcreteMediator* self = (ConcreteMediator*)obj;
printf("%s received message: %sn", self->name, message);
}
ConcreteMediator createConcreteMediator(char* name) {
ConcreteMediator mediator;
mediator.mediator.notify = ConcreteMediator_notify;
mediator.name = malloc(strlen(name) + 1);
strcpy(mediator.name, name);
return mediator;
}
// 抽象同事类
typedef struct {
void (*send)(void*, char*);
void (*receive)(void*, char*);
} Colleague;
// 具体同事类
typedef struct {
Colleague colleague;
Mediator* mediator;
char* name;
} ConcreteColleague;
void ConcreteColleague_send(void* obj, char* message) {
ConcreteColleague* self = (ConcreteColleague*)obj;
printf("%s sends message: %sn", self->name, message);
self->mediator->notify(self->mediator, message);
}
void ConcreteColleague_receive(void* obj, char* message) {
ConcreteColleague* self = (ConcreteColleague*)obj;
printf("%s received message: %sn", self->name, message);
}
ConcreteColleague createConcreteColleague(char* name, Mediator* mediator) {
ConcreteColleague colleague;
colleague.colleague.send = ConcreteColleague_send;
colleague.colleague.receive = ConcreteColleague_receive;
colleague.mediator = mediator;
colleague.name = malloc(strlen(name) + 1);
strcpy(colleague.name, name);
return colleague;
}
int main() {
ConcreteMediator mediator = createConcreteMediator("Mediator");
ConcreteColleague colleague1 = createConcreteColleague("Colleague1", &mediator.mediator);
ConcreteColleague colleague2 = createConcreteColleague("Colleague2", &mediator.mediator);
colleague1.colleague.send(&colleague1, "Hello, Colleague2!");
colleague2.colleague.send(&colleague2, "Hi, Colleague1!");
free(mediator.name);
free(colleague1.name);
free(colleague2.name);
return 0;
}
在上面的示例代码中,定义了中介者接口Mediator
和具体中介者类ConcreteMediator
,实现了通知方法来处理同事对象之间的交互。
同时还定义了抽象同事类Colleague
和具体同事类ConcreteColleague
,实现了发送和接收方法,并通过中介者对象来处理同事之间的交互。
在main
函数中,首先创建了一个具体中介者对象mediator
,然后创建了两个具体同事对象colleague1
和colleague2
,并将中介者对象传入。
然后通过调用同事对象的发送方法来向另一个同事对象发送消息,中介者对象将处理这些消息,最后输出了结果。
中介者模式的优点:
中介者模式的缺点:
适用场景:
原文地址:https://blog.csdn.net/qq_32059343/article/details/134751476
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_48608.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!