Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1455835
  • 博文数量: 596
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 173
  • 用 户 组: 普通用户
  • 注册时间: 2016-07-06 15:50
个人简介

在线笔记

文章分类

全部博文(596)

文章存档

2016年(1)

2015年(104)

2014年(228)

2013年(226)

2012年(26)

2011年(11)

分类: 架构设计与优化

2013-10-25 15:08:21


  1. /**-----------------------------------------------------------------------------
  2.  * @file main.cpp
  3.  *
  4.  * @author @.com.cn
  5.  *
  6.  * @date 2013-10-25
  7.  *
  8.  * @brief
  9.  *
  10.  * @version
  11.  *
  12.  *----------------------------------------------------------------------------*/
  13. #include <iostream>
  14. #include <list>
  15. #include <algorithm>

  16. using namespace std;

  17. class subject;
  18. /* 观察者抽象类 */
  19. class observer
  20. {
  21. public:
  22.     virtual void update(subject *sub) {};
  23. };

  24. /* 对象抽象类 */
  25. /* 解析:
  26.  * (1)3个函数都有默认实现, 不使用纯虚的,否则子类要重新实现
  27.  * (2)list<observer*> m_observerList; list存放observer*类型,
  28.  * (3)扩展:纯虚类不能作为变量类型
  29.             class a{
  30.                 virtual void f() = 0;
  31.             };
  32.             a b;
  33.  */
  34. class subject
  35. {
  36. public:
  37.     virtual void attach(observer* o);
  38.     virtual void detach(observer* o);
  39.     virtual void notify();
  40. private:
  41.     list<observer*> m_observerList;
  42. };

  43. void subject::attach(observer* o)
  44. {
  45.     m_observerList.push_back(o);
  46. }

  47. void subject::detach(observer* o)
  48. {
  49.     m_observerList.remove(o);
  50. }

  51. /* list遍历 */
  52. void subject::notify()
  53. {
  54.     list<observer*>::iterator it;
  55.     for ( it = m_observerList.begin();
  56.           it != m_observerList.end();
  57.           it++ )
  58.     {
  59.         (*it)->update(this);
  60.     }
  61. }



  62. /* 对象 */
  63. class newsStand : public subject
  64. {
  65. public:
  66.     void setState(int state);
  67.     int getState();

  68. private:
  69.     int m_state;
  70. };

  71. void newsStand::setState(int state)
  72. {
  73.     m_state = state;
  74.     notify();
  75. }

  76. int newsStand::getState()
  77. {
  78.     return m_state;
  79. }

  80. /* 观察者 */
  81. class student : public observer
  82. {
  83. public:
  84.     void update(subject *sub)
  85.     {
  86.         cout << m_name << " get notice, state = " << ((newsStand*)sub)->getState() << endl;
  87.     }

  88.     student(string name)
  89.     {
  90.         m_name = name;
  91.     }

  92.     ~student()
  93.     {
  94.     }
  95. private:
  96.     string m_name;
  97. };

  98. int main(int argc, char **argv)
  99. {
  100.     newsStand s;
  101.     student s1("lucy");
  102.     student *s2 = new student("mike");
  103.     s.attach(&s1);
  104.     s.attach (s2);
  105.     s.setState(2);

  106.     return 0;
  107. }
参考:http://sishuok.com/forum/blogPost/list/5279.html
研磨设计模式 之 观察者模式(Observer) 1——跟着cc学设计系列 

阅读(891) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~