/* Andy is going to hold a concert while the time is not decided. Eric is a fans of Andy who doesn't want to miss this concert. Andy doesn't know Eric. How can Eric gets the news when Andy's concert is going to take? */ /* Singer:被观察者 Fans:观察者 */ #include "stdafx.h" #include <iostream> #include <boost/signals2.hpp> #include <boost/bind.hpp> #include <string> using namespace std; struct Singer { //定义信号的类型,也就是说 Singer 需要知道 Fans 的响应方式 //也就是说 Singer 需要知道 Fans 会采用什么样的方式来响应 Singer 所发出的信号 //或者说 Singer 需要知道 Fans 用什么样的方式来接受 Singer 发出的信号 //就相当于 Singer 需要知道 Fans的“邮箱”,到时候才可以将信息投递到 Fans 的“邮箱”类型中去 //Fans 的“邮箱”类型—— void (string time) typedef boost::signals2::signal<void (string time)> signalType; typedef signalType::slot_type slotType; signalType m_signal; //定义一个信号 //Singer 发布信号 void PublishTime(string time) { m_signal(time); //将包含 time 信息的信号m_signal投递到 Fans 的邮箱中去,注意,投递之前这种类型的邮箱必须要和一个具体的Fans联系起来,即必须知道是谁拥有这种类型的邮箱,这一动作通过后边的Subscribe实现。 } //Singer 提供一种注册渠道:Fans们可以通过这个渠道来进行注册,告诉Singer,有新信号的话就发送给我一个消息 boost::signals2::connection Subscribe(const slotType& fans) {//在这里将Fans与Singer建立起一种联系(connection) //到后面可以发现,Fans需要调用这个函数,即通过这个渠道告诉Singer有消息就要通知给我 return m_signal.connect(fans); } }; struct Fans { // m_connection:联系的存在是在整个Fans的生命周期内的,一旦Fans消失,这种联系也就不复存在了 boost::signals2::scoped_connection m_connection; //Fans的响应方式,也就是Fans的邮箱类型,至于里面具体做什么事情,Singer不需要知道。 void Correspond(string time) { cout<<"I know the concert time: "<<time<<endl; } //Fans需要自己确定他要关注(观察)哪一个Singer 的动向 void Watch(Singer& singer) { //通过调用Singer的Subscribe函数(渠道)来将自己的邮箱地址告知Singer m_connection = singer.Subscribe(boost::bind(&Fans::Correspond, this, _1)); } }; int main(int argc, char* argv[]) { Singer Andy; //刘德华 Fans Eric; //Eric Eric.Watch(Andy); //Eric告知刘德华:我要关注你的动向,请把你的最新信息发给我 Andy.PublishTime("2010/10/01");//刘德华发布最新信息,一旦信息发布,Eric的邮箱——void Correspond(string time)就会接受到信息,并进行响应——cout<<…. return 0; } Reference: http://www.cppprog.com/boost_doc/doc/html/signals2/tutorial.html http://www.cppprog.com/2009/0430/111.html http://www.cppprog.com/boost_doc/