BOOST::Signals2

时间:2023-03-09 08:03:36
BOOST::Signals2
  1. /*
  2. Andy is going to hold a concert while the time is not decided.
  3. Eric is a fans of Andy who doesn't want to miss this concert.
  4. Andy doesn't know Eric.
  5. How can Eric gets the news when Andy's concert is going to take?
  6. */
  7. /*
  8. Singer:被观察者
  9. Fans:观察者
  10. */
  11. #include "stdafx.h"
  12. #include <iostream>
  13. #include <boost/signals2.hpp>
  14. #include <boost/bind.hpp>
  15. #include <string>
  16. using namespace std;
  17. struct Singer
  18. {
  19. //定义信号的类型,也就是说 Singer 需要知道 Fans 的响应方式
  20. //也就是说 Singer 需要知道 Fans 会采用什么样的方式来响应 Singer 所发出的信号
  21. //或者说 Singer 需要知道 Fans 用什么样的方式来接受 Singer 发出的信号
  22. //就相当于 Singer 需要知道 Fans的“邮箱”,到时候才可以将信息投递到 Fans 的“邮箱”类型中去
  23. //Fans 的“邮箱”类型—— void (string time)
  24. typedef boost::signals2::signal<void (string time)> signalType;
  25. typedef signalType::slot_type slotType;
  26. signalType m_signal; //定义一个信号
  27. //Singer 发布信号
  28. void PublishTime(string time)
  29. {
  30. m_signal(time); //将包含 time 信息的信号m_signal投递到 Fans 的邮箱中去,注意,投递之前这种类型的邮箱必须要和一个具体的Fans联系起来,即必须知道是谁拥有这种类型的邮箱,这一动作通过后边的Subscribe实现。
  31. }
  32. //Singer 提供一种注册渠道:Fans们可以通过这个渠道来进行注册,告诉Singer,有新信号的话就发送给我一个消息
  33. boost::signals2::connection Subscribe(const slotType& fans)
  34. {//在这里将Fans与Singer建立起一种联系(connection)
  35. //到后面可以发现,Fans需要调用这个函数,即通过这个渠道告诉Singer有消息就要通知给我
  36. return m_signal.connect(fans);
  37. }
  38. };
  39. struct Fans
  40. {
  41. // m_connection:联系的存在是在整个Fans的生命周期内的,一旦Fans消失,这种联系也就不复存在了
  42. boost::signals2::scoped_connection m_connection;
  43. //Fans的响应方式,也就是Fans的邮箱类型,至于里面具体做什么事情,Singer不需要知道。
  44. void Correspond(string time)
  45. {
  46. cout<<"I know the concert time: "<<time<<endl;
  47. }
  48. //Fans需要自己确定他要关注(观察)哪一个Singer 的动向
  49. void Watch(Singer& singer)
  50. {
  51. //通过调用Singer的Subscribe函数(渠道)来将自己的邮箱地址告知Singer
  52. m_connection = singer.Subscribe(boost::bind(&Fans::Correspond, this, _1));
  53. }
  54. };
  55. int main(int argc, char* argv[])
  56. {
  57. Singer  Andy; //刘德华
  58. Fans    Eric; //Eric
  59. Eric.Watch(Andy); //Eric告知刘德华:我要关注你的动向,请把你的最新信息发给我
  60. Andy.PublishTime("2010/10/01");//刘德华发布最新信息,一旦信息发布,Eric的邮箱——void Correspond(string time)就会接受到信息,并进行响应——cout<<….
  61. return 0;
  62. }

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/