A:“我想租房,价位1500左右。”
中介:“好的,我这边有房源。什么时候过来看看,价钱划算。”
B:“我这边有闲置房间,想租出去,2000以上。”
中介:“可以的,我这边有客户。价钱好商量。”
中介---A:“房东B说了,低于2000不可以。”
中介---B:“客户A说了,高于18000,就太高了,不想考虑。”
......
尽管讲一个系统分割成所需对象,通常可以增加其复用性。但是对象间相互连接的激增,会降低其复用性。尤其是大量链接,会使得系统耦合性增加,对系统的改动,将会变得复杂和困难。这时可以考虑中介者模式。
中介者不参与实际声明,只负责传递消息。优点:集中控制,降低各个对象间的耦合。缺点:集中控制,使得中介者变得复杂。如果系统出现了多对多交互复杂的对象群时,不要急于使用该模式,而是想想是不是系统设计上存在不合理。总的来说该模式相对比较鸡肋。
#pragma once
#include<iostream>
#include<string>
using std::string;
class Country;
//中介者抽象
class UniteNations
{
public:
virtual void declare(string messasge ,const Country* country){ }
virtual ~UniteNations(){}
protected:
};
//具体对象
class Country
{
public:
Country(UniteNations * unite) :m_unite(unite)
{
}
virtual~Country(){}
protected:
UniteNations * m_unite;
};
class USA : public Country
{
public:
USA(UniteNations * unite) :Country(unite)
{
}
void declare(string msg)
{
m_unite->declare(msg,this);
}
void getmsg(string msg)
{
printf("USA获得消息:%s\n", msg.c_str());
}
};
class IRAQ : public Country
{
public:
IRAQ(UniteNations * unite) :Country(unite)
{
}
void declare(string msg)
{
m_unite->declare(msg, this);
}
void getmsg(string msg)
{
printf("IRAQ获得消息:%s\n", msg.c_str());
}
};
//具体中介者
class UniteSecurityCouncil :public UniteNations
{
public:
void setUSA(USA *usa)
{
m_usa = usa;
}
void setIRAQ(IRAQ *iraq)
{
m_iraq = iraq;
}
void declare(string messasge, const Country* country)
{
if (country==m_usa)
{
m_iraq->getmsg(messasge);
}
else
{
m_usa->getmsg(messasge);
}
}
private:
USA *m_usa;
IRAQ *m_iraq;
};
int main()
{
UniteSecurityCouncil unsc;
USA usa(&unsc);
IRAQ iraq(&unsc);
unsc.setUSA(&usa);
unsc.setIRAQ(&iraq);
usa.declare("把石油给我,否则发动战争!");
iraq.declare("艹,你以为老子威胁大的?");
return 0;
}