设计模式–中介者模式
思路
设计一个中间类,给多个类之间充当桥梁。
优点
1.解耦状态和行为:将多个对象之间的复杂交互集中在一个中介者对象中进行管理。各个对象之间不再需要直接相互引用,而是通过中介者进行通信。这大大降低了对象之间的耦合度,使得系统更加灵活和易于维护。
2.增强可维护性和可扩展性:当需要添加新的对象或修改现有对象的行为时,只需要在中介者对象中进行相应的修改,而不会影响到其他对象。这使得系统具有良好的可扩展性。
3.集中控制交互:中介者对象可以集中控制多个对象之间的交互逻辑。它可以协调对象之间的行为,确保交互的正确性和一致性。
设计
有想要买房和卖房的两种人,但是他们的时间都不是很充足,所以为了方便,都选择找了中介。都不需要管对方是什么人,他们只需要跟中介沟通就行。
class Mediator {//中介抽象接口
public:
virtual void notify(User* sender) = 0;
};
class User{//用户抽象接口
protected:
Mediator* mediator;
public:
User(Mediator* m) : mediator(m) {}
virtual void sendMessage() = 0;
};
#include <vector>
class HouseMediator : public Mediator {//具体中介类
private:
std::vector<User*> users;
Buyer* buyer;
Seller* seller;
public:
void User(User* user) {
users.push_back(user);
if (dynamic_cast<Buyer*>(user)) {
buyer = static_cast<Buyer*>(user);
} else if (dynamic_cast<Seller*>(user)) {
seller = static_cast<Seller*>(user);
}
}
void notify(User* sender) override {
if (sender == buyer) {
if (seller && seller->isSelling()) {
std::cout << "Mediator: Buyer wants to buy. Seller is selling. Deal can be made." << std::endl;
} else {
std::cout << "Mediator: Buyer wants to buy. But no seller available." << std::endl;
}
} else if (sender == seller) {
if (buyer && buyer->isBuying()) {
std::cout << "Mediator: Seller is selling. Buyer is buying. Deal can be made." << std::endl;
} else {
std::cout << "Mediator: Seller is selling. But no buyer available." << std::endl;
}
}
}
};
class Buyer : public User{//买房用户
private:
bool isBuying;
public:
Buyer(Mediator* m) : User(m), isBuying(false) {}
void startBuying() {
isBuying = true;
sendMessage();
}
bool isBuyingNow() const {
return isBuying;
}
void sendMessage() override {
mediator->notify(this);
}
};
class Seller : public User{//卖房用户
private:
bool isSelling;
public:
Seller(Mediator* m) : User(m), isSelling(false) {}
void startSelling() {
isSelling = true;
sendMessage();
}
bool isSellingNow() const {
return isSelling;
}
void sendMessage() override {
mediator->notify(this);
}
};
int main() {
HouseMediator mediator;
Buyer buyer(&mediator);
Seller seller(&mediator);
mediator.registerUser(&buyer);
mediator.registerUser(&seller);
buyer.startBuying();
seller.startSelling();
return 0;
}
先是创建了中介类,然后有买房人和卖房人,都要跟中介添加联系方式才能沟通,然后才能进行对应操作。
不过这个代码没有考虑多个用户的情况,可以在注册用户的时候加入一个唯一标识,然后在进行操作的时候可以指定,也可以不指定,用循环的方式广播。