发布订阅者模式c++实现

来源:互联网 发布:实施网络攻击的前提 编辑:程序博客网 时间:2024/06/06 10:43


#ifndef BOTTON_H
#define BOTTON_H

#include <string>
#include <vector>

class BottonListener;
class Botton
{
public:
 Botton(const std::string & botton_name);
 ~Botton();
 const std::string & GetName() const;
 void AddBottonListener(BottonListener * botton_listener);
 void RemoveBottonListenner(BottonListener * botton_listener);
 void Run();
private:
 typedef std::vector<BottonListener*>::iterator ITER;
 std::string name_;
 std::vector<BottonListener*> listener_vector_;
};
#endif/*BOTTON_H*/

 

 


#ifndef BOTTON_LISTENER_H
#define BOTTON_LISTENER_H

class Botton;
class BottonListener
{
public:
 BottonListener();
 virtual ~BottonListener();
 virtual void BottonClick(Botton * botton) = 0;
};
#endif/*BOTTON_LISTENER_H*/

 

 

#ifndef MY_BOTTON_LISTENER_H
#define MY_BOTTON_LISTENER_H

#include "botton_listener.h"
#include "botton.h"

class MyBottonListener : public BottonListener
{
public:
 MyBottonListener(int number);
 ~MyBottonListener();
 void BottonClick(Botton * botton);
private:
 int number_;
};

#endif/*MY_BOTTON_LISTENER_H*/

 


#include "botton_listener.h"
#include "botton.h"

Botton::Botton(const std::string &botton_name) : name_(botton_name)
{

}

Botton::~Botton()
{

}

const std::string & Botton::GetName() const
{
 return this->name_;
}

void Botton::AddBottonListener(BottonListener * botton_listener)
{
 this->listener_vector_.push_back(botton_listener);
}

void Botton::RemoveBottonListenner(BottonListener * botton_listener)
{
 bool key = false;
 ITER iter;
 for(iter = listener_vector_.begin();iter != listener_vector_.end();iter++)
 {
  if(*iter == botton_listener )
  {
   key = true;
   break;
  }
 }
 if(key)
 {
  listener_vector_.erase(iter);
 }
}

void Botton::Run()
{
 for(ITER iter = listener_vector_.begin(); iter != listener_vector_.end(); iter++)
 {
  BottonListener * p_botton_listener = *iter;
  p_botton_listener->BottonClick(this);
 }
}

 

 

#include "botton_listener.h"

BottonListener::BottonListener()
{

}

BottonListener::~BottonListener()
{

}

 


#include <iostream>
#include "my_botton_listener.h"

MyBottonListener::MyBottonListener(int number) : number_(number)
{

}

MyBottonListener::~MyBottonListener()
{

}

void MyBottonListener::BottonClick(Botton *botton)
{
 std::cout<<botton->GetName()<<" "<<number_<<std::endl;
}


 


#include "botton_listener.h"
#include "botton.h"
#include "my_botton_listener.h"

int main(int argc,char **argv)
{
 Botton *botton = new Botton("Hello!");
 BottonListener *botton_listener_1 = new MyBottonListener(1);
 BottonListener *botton_listener_2 = new MyBottonListener(2);

 botton->AddBottonListener(botton_listener_1);
 botton->AddBottonListener(botton_listener_2);

 botton->Run();
 
 botton->RemoveBottonListenner(botton_listener_1);
 botton->RemoveBottonListenner(botton_listener_2);
 delete botton;
 delete botton_listener_1;
 delete botton_listener_2;

}