中介者模式: 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: %s\n", 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: %s\n", self->name, message);
self->mediator->notify(self->mediator, message);
}
void ConcreteColleague_receive(void* obj, char* message) {
ConcreteColleague* self = (ConcreteColleague*)obj;
printf("%s received message: %s\n", 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
,并将中介者对象传入。
然后通过调用同事对象的发送方法来向另一个同事对象发送消息,中介者对象将处理这些消息,最后输出了结果。
中介者模式的优点:
-
可以减少对象之间的直接依赖关系,使代码更加灵活,易于维护。
-
可以集中控制对象之间的交互逻辑,使代码更加清晰简洁。
-
可以降低系统的复杂度,提高系统的可维护性和可扩展性。
中介者模式的缺点:
-
中介者对象需要处理多个对象之间的交互逻辑,可能会导致中介者对象变得复杂。
-
中介者对象的存在会增加系统的开销,因为需要维护额外的对象和逻辑。
适用场景:
-
对象之间的交互逻辑比较复杂,存在大量的依赖关系。
-
对象之间的交互逻辑经常发生变化,需要进行频繁的修改。
-
系统的对象之间存在多对多的关系,难以维护。