Callbacks in C++


abstract client

//----------------------------------------
// l i b r a r y c o d e
//----------------------------------------
class Button;

class ButtonClient
{
public:
  virtual void buttonPushed(Button*) = 0;
};
//----------------------------------------
class Button
{
public:
  Button(ButtonClient* pClient_):_pClient(pClient_){}
  void push() {_pClient->buttonPushed(this);}
private:
  ButtonClient* _pClient;
};
//----------------------------------------
// c l i e n t c o d e
//----------------------------------------
#include <iostream.h>
class CdPlayer:
public ButtonClient
{
public:
  /*virtual*/ void buttonPushed(Button* pButton_)
  { 
    if (pButton_ == _pPlayButton)
      this->playButtonPushed(pButton_);
    else if (pButton_ == _pStopButton)
      this->stopButtonPushed(pButton_);
  }

  void setPlayButton(Button* pButton_) {_pPlayButton = pButton_;}
  void setStopButton(Button* pButton_) {_pStopButton = pButton_;}
  void playButtonPushed(Button*) {cout << "PLAY" << endl;}
  void stopButtonPushed(Button*) {cout << "STOP" << endl;}

private:
  Button* _pPlayButton;
  Button* _pStopButton; 
};
//----------------------------------------
main()
{
  CdPlayer aCdPlayer;
  Button playButton(&aCdPlayer);
  Button stopButton(&aCdPlayer);
  aCdPlayer.setPlayButton(&playButton);
  aCdPlayer.setStopButton(&stopButton);
  playButton.push();
  stopButton.push();
  return 0;
};

[View/Add Comments]


Callbacks in C++
Copyright © 1996-2000 Paul Jakubik
Created: 26 July 1996. Last update: 26 November 2000.
pauljakubik@yahoo.com