码迷,mamicode.com
首页 > 编程语言 > 详细

设计模式——观察者模式(C++实现)

时间:2017-05-12 23:11:57      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:ase   get   using   pattern   sig   ++   cout   分享   ios   

技术分享

技术分享

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <iterator>
 5 #include <string>
 6 
 7 using namespace std;
 8 
 9 class STSubject;
10 
11 //观察者
12 class STObserver
13 {
14 public:
15         virtual void Update() = 0;
16 };
17 
18 class STConcreteObserverA: public STObserver
19 {
20 public:
21         virtual void Update()
22         {
23                 cout<< "ConcreteObserverA Get Subject: "<< endl;
24         }
25 };
26 
27 class STConcreteObserverB: public STObserver
28 {
29 public:
30         virtual void Update()
31         {
32                 cout<< "ConcreteObserverB Get Subject: "<< endl;
33         }
34 };
35 
36 
37 //目标
38 class STSubject
39 {
40 public:
41         void Attach(STObserver* pstObserver)
42         {
43                 m_vecObj.push_back(pstObserver);
44         }
45         void Detach(STObserver* pstObserver)
46         {
47                 typeof(m_vecObj.begin()) it = find(m_vecObj.begin(), m_vecObj.end(), pstObserver);
48                 if (it != m_vecObj.end())
49                         m_vecObj.erase(it);
50         }
51         void Notify()
52         {
53                 for (size_t i = 0; i < m_vecObj.size(); i++)
54                 {
55                         m_vecObj[i]->Update();
56                 }
57         }
58 
59         virtual string GetName() = 0;
60 
61 private:
62         vector<STObserver*> m_vecObj;
63 };
64 
65 class STConcreteSubjectA: public STSubject
66 {
67 public:
68         virtual string GetName()
69         {
70                 return "ConcreteSubjectA";
71         }
72 
73 };
74 
75 int main(int argc, char* argv[])
76 {
77         STSubject* pstSubjectA = new STConcreteSubjectA();
78         STObserver* pstObserverA = new STConcreteObserverA();
79         STObserver* pstObserverB = new STConcreteObserverB();
80 
81         pstSubjectA->Attach(pstObserverA);
82         pstSubjectA->Attach(pstObserverB);
83 
84         pstSubjectA->Notify();
85 
86         pstSubjectA->Detach(pstObserverB);
87         pstSubjectA->Notify();
88 
89         return 0;
90 }
91 //////////////////////////////////
92 [root@ ~/learn_code/design_pattern/12_observer]$ ./observer       
93 ConcreteObserverA Get Subject:
94 ConcreteObserverB Get Subject:
95 ConcreteObserverA Get Subject:

 

设计模式——观察者模式(C++实现)

标签:ase   get   using   pattern   sig   ++   cout   分享   ios   

原文地址:http://www.cnblogs.com/070412-zwc/p/6847454.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!