01 |
#include <iostream> |
02 |
#include <string> |
03 |
#include <vector> |
04 |
#include <algorithm> |
05 |
using namespace std;
|
06 |
07 |
class button;
|
08 |
09 |
struct button_listener{
|
10 |
button_listener(){}
|
11 |
virtual ~button_listener(){}
|
12 |
virtual void button_clicked(button* btn)=0;
|
13 |
}; |
14 |
15 |
class button{
|
16 |
private :
|
17 |
vector<button_listener*> listeners;
|
18 |
typedef vector<button_listener*>::iterator bit_type;
|
19 |
string name;
|
20 |
public :
|
21 |
string get_name(){ return name;};
|
22 |
button(string n):name(n){}
|
23 |
~button(){}
|
24 |
void add_button_listener(button_listener* bls){
|
25 |
listeners.push_back(bls);
|
26 |
}
|
27 |
void remove_button_listener(button_listener* bls){
|
28 |
listeners.erase( remove (
|
29 |
listeners.begin(),listeners.end(),bls),
|
30 |
listeners.end());
|
31 |
}
|
32 |
void run(){
|
33 |
for (bit_type it=listeners.begin();it!=listeners.end();++it){
|
34 |
button_listener* bls = *it;
|
35 |
bls->button_clicked( this );
|
36 |
}
|
37 |
}
|
38 |
}; |
39 |
40 |
41 |
class my_button_listener: public button_listener{
|
42 |
private :
|
43 |
int i;
|
44 |
public :
|
45 |
my_button_listener( int ii):i(ii){}
|
46 |
void button_clicked(button* btn){
|
47 |
cout<<btn->get_name()<< " " <<i<<endl;
|
48 |
}
|
49 |
}; |
50 |
51 |
int main(){
|
52 |
button* btn = new button( "nihao" );
|
53 |
button_listener* bls1 = new my_button_listener(1);
|
54 |
button_listener* bls2 = new my_button_listener(2);
|
55 |
|
56 |
btn->add_button_listener(bls1);
|
57 |
btn->add_button_listener(bls2);
|
58 |
btn->run();
|
59 |
60 |
btn->remove_button_listener(bls1);
|
61 |
btn->run();
|
62 |
63 |
delete btn;
|
64 |
delete bls1;
|
65 |
delete bls2;
|
66 |
return 0;
|
67 |
} |
本文转自博客园知识天地的博客,原文链接:c++ 观察者模式,如需转载请自行联系原博主。