❝用一个中介对象来封装一系列对象的交互,从而把一批原来可能是交互关系复杂的对象转换成一组松散耦合的中间对象,以有利于维护和修改。
中介者模式是将**「多对多」的交互关系转化为「一对多」**。软件中设计一个中介对象专门管理交互逻辑,如此一来便能够将各个对象间错综复杂的耦合统一到与中介对象耦合。
从图上看,飞机之间关系相当复杂。降落飞机需要向所有的飞机发送请求信息并等待应答,效率低下。
为提高效率,引入塔台角色。塔台事先与其他飞机交互保存各个飞机的信息,当有飞机发送降落请求时,塔台根据保存的信息应答降落请求即可。如此一来,大大提升了交互效率。
这里以塔台案例为案例绘制UML类图。
本源码只实现了塔台与飞机间的交互框架,具体的飞机停靠业务逻辑没有体现。
「客户端代码」
int main(int argc, char *argv[])
{
CChengduTowerMediator *theChengduTower = CChengduTowerMediator::GetInstance();
CAirBusA319 *theAirBus319 = new CAirBusA319();
theAirBus319->SetMediator(theChengduTower);
CBoeing737 *theBoeing737 = new CBoeing737();
theBoeing737->SetMediator(theChengduTower);
CComacC919 *theCComacC919 = new CComacC919();
theCComacC919->SetMediator(theChengduTower);
// 塔台向所有飞机广播,通报姓名
//MAIN_LOGI("--> Tower Radio: notify name\n");
theChengduTower->NotifyObserverAll((char *)"Please notify your name");
MAIN_LOG("\n");
// AirBus319应答塔台
//MAIN_LOGI("--> AirBus319 Notify\n");
theAirBus319->Notify((char *)"This is AirBus319");
MAIN_LOG("\n");
// theBoeing737应答塔台
//MAIN_LOGI("--> Boeing737 Notify\n");
theBoeing737->Notify((char *)"This is Boeing737");
MAIN_LOG("\n");
// CComacC919应答塔台
//MAIN_LOGI("--> CComacC919 Notify\n");
theCComacC919->Notify((char *)"This is CComacC919");
MAIN_LOG("\n");
delete theAirBus319;
delete theBoeing737;
delete theCComacC919;
return 0;
}
「执行效果」
$ ./exe
[CAirBusA319] Recv: Please notify your name
[CBoeing737] Recv: Please notify your name
[CComacC919] Recv: Please notify your name
Tower Recv: [0] This is AirBus319
[CAirBusA319] Recv: Ack
Tower Recv: [1] This is Boeing737
[CBoeing737] Recv: Ack
Tower Recv: [2] This is CComacC919
[CComacC919] Recv: Ack
「塔台接口」
class CChengduTowerMediator : public CTowerMediatorBase
{
public:
CChengduTowerMediator();
~CChengduTowerMediator();
static CChengduTowerMediator* GetInstance();
// 注册飞机实例
int Register(CAirplaneBase* airplane);
// 注销指定飞机ID
int UnRegister(int RegisterId);
// 向指定飞机发送消息
int SendMsg(int RegisterId, void *msg);
// 向所有注册飞机发送广播
int NotifyObserverAll(void *msg);
// 接收飞机消息
int Receive(int id, void *msg);
private:
// 飞机注册表
std::map<int, CAirplaneBase*> mAirplaneHashTable;
};
「飞机接口」
class CAirBusA319 : public CAirplaneBase
{
public:
CAirBusA319();
~CAirBusA319();
void SetMediator(CTowerMediatorBase *meditor);
int Notify(void *msg);
int Receive(void *msg);
private:
int mIdForMediator;
CTowerMediatorBase *pmMeditor;
};
阅读量:2020
点赞量:0
收藏量:0