监听者对大家来说可能并不陌生,所谓监听者就是用来监听自已感兴趣的事件的,当收到自已感兴趣的事件时会做出相应的反映。
event 1 is fired.
event 1 is fired.
==========================
event 2 is fired.
event 2 is fired.
==========================
other event is fired.
other event is fired.
==========================
它的应用是非常广的,比如win32的消息机制,它跟监听者模式就异曲同工,操作系统将产生的各种事件包装成消息(msg),该消息结构包装了发生的事件的描述信息,比如消息值,屏幕坐标等,然后将它投递到相应的进程中,当该进程收到该消息时会查看该msg结构中的信息,也就知道了发生了什么事件,并对自已感兴趣的事件进行响应。
下面我们就来用c++实现一个简单的监听者
- #include <iostream>
- using namespace std;
- //listener基类(抽象类)
- class abstractlistener
- {
- public:
- abstractlistener(){};
- virtual ~abstractlistener(){};
- virtual void actionperformed(int state) = 0;
- };
- //listener实现类(它类似于操作系统中的进程)
- class statelistener:public abstractlistener
- {
- public:
- statelistener(){};
- virtual ~statelistener(){};
- virtual void actionperformed(int state);
- };
- void statelistener::actionperformed(int state)
- {
- //这里就是对自已感兴趣的事件的相应处理
- if(state==1){
- cout<<"event 1 is fired."<<endl;
- }else if(state==2){
- cout<<"event 2 is fired."<<endl;
- }else{
- cout<<"other event is fired."<<endl;
- }
- }
- //listener center(类似于操作系统(os))
- class listenercenter
- {
- private:
- statelistener listenerlist[50];//存储listener的数组
- int count;//当前中心中已有的listener的个数
- public:
- listenercenter();
- virtual ~listenercenter(){};
- int getcount();
- void addlistener(statelistener);
- void firestatelistener(int state);
- };
- listenercenter::listenercenter()
- {
- this->count=0;
- }
- int listenercenter::getcount()
- {
- return count;
- }
- void listenercenter::addlistener(statelistener statelistener)
- {
- listenerlist[this->count]=statelistener;
- this->count++;
- }
- void listenercenter::firestatelistener(int state)
- {
- for(int i=0;i<this->count;i++){
- listenerlist[i].actionperformed(state);
- }
- }
- int main(int argc, char* argv[])
- {
- listenercenter listenercenter;
- statelistener statelis1;
- statelistener statelis2;
- listenercenter.addlistener(statelis1);
- listenercenter.addlistener(statelis2);
- cout<<"=========================="<<endl;
- listenercenter.firestatelistener(1);
- cout<<"=========================="<<endl;
- listenercenter.firestatelistener(2);
- cout<<"=========================="<<endl;
- listenercenter.firestatelistener(3);
- cout<<"=========================="<<endl;
- return 0;
- }
打印:
==========================event 1 is fired.
event 1 is fired.
==========================
event 2 is fired.
event 2 is fired.
==========================
other event is fired.
other event is fired.
==========================