抽象中介者(Mediator):抽象中介者角色定义统一的接口,用于各同事角色之间的通信。
抽象同事类(Colleague ):每一个同事角色都知道中介者角色,而且与其它的同事角色通信的时候,一定要通过中介者角色协作。每个同事类的行为分两种:一种是同事本身行为,比如改变对象本身的状态,处理自己的行为等,这种行为叫做自发行为,与其它同事类或者中介者没有任何依赖;第二种是必须依赖中介者才能完成的行为,叫做依赖方法。
具体中介者类(Concrete Mediator):具体中介者角色通过协调各同事角色实现协作行为,因此它必须依赖于各个同事角色。
具体同事类(Concrete Colleague):这里以ConcreteColleague1为例,ConcreteColleague2不再赘述。
代码:
#include <iostream>
using namespace std;
class Colleague;
//定义一个中介者接口,包含对象改变所需调用函数。
class Mediator
{
public:
virtual ~Mediator()
{
}
virtual void changed(Colleague *) = 0;
};
//定义"同事"类接口,初始化需要一个中介者对象,并通过该类更新另外一个"同事"
class Colleague
{
public:
//初始化中介者类对象
Colleague(Mediator * mediator)
{
this->mediator = mediator;
}
//更新另外一个类
virtual void changed()
{
mediator->changed(this);
}
private:
Mediator *mediator;
};
//具体的同事类1
class ConcreteColleague1 :public Colleague
{
public:
ConcreteColleague1(Mediator * mediator) :Colleague(mediator)
{
}
void update()
{
cout << "update ConcreteColleague1 from ConcreteColleague2" << endl;
}
};
//具体的同事类2
class ConcreteColleague2 :public Colleague
{
public:
ConcreteColleague2(Mediator * mediator) :Colleague(mediator)
{
}
void update()
{
cout << "update ConcreteColleague2 from ConcreteColleague1" << endl;
}
};
//具体的中介者类,实现更新函数changed。
class ConcreteMediator :public Mediator
{
private:
ConcreteColleague1 * colleague1;
ConcreteColleague2 * colleague2;
public:
void setColleague1(ConcreteColleague1 * colleague)
{
colleague1 = colleague;
}
void setColleague2(ConcreteColleague2 * colleague)
{
colleague2 = colleague;
}
ConcreteMediator()
{
//colleague1 = new ConcreteColleague1(this);
}
~ConcreteMediator()
{
}
virtual void changed(Colleague* colleague)
{
if (colleague == colleague1)
{
colleague2->update();
}
else if (colleague == colleague2)
{
colleague1->update();
}
else;
}
};
int main()
{
ConcreteMediator concreteMediator;
ConcreteColleague1 colleague1(&concreteMediator);
ConcreteColleague2 colleague2(&concreteMediator);
concreteMediator.setColleague1(&colleague1);
concreteMediator.setColleague2(&colleague2);
//"同事1"通过中介者更新"同事2"
colleague1.changed();
//"同事2"通过中介者更新"同事1"
colleague2.changed();
getchar();
return 0;
}
输出:
pdate ConcreteColleague2 from ConcreteColleague1
update ConcreteColleague1 from ConcreteColleague2
参考:
https://www.guyuehome.com/38376
标签:Colleague,mediator,ConcreteColleague1,Mediator,同事,模式,中介 From: https://www.cnblogs.com/huvjie/p/16705301.html