Callbacks in C++


adapter

//----------------------------------------
// 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:
  void playButtonPushed(Button*) {cout << "PLAY" << endl;}
  void stopButtonPushed(Button*) {cout << "STOP" << endl;}
};
//----------------------------------------
class CdPlayerAdapter:
  public ButtonClient,
  private CdPlayer
{
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_;}

private:
  Button* _pPlayButton;
  Button* _pStopButton;
};
//----------------------------------------
main()
{
  CdPlayerAdapter aCdPlayerAdapter;

  Button playButton(&aCdPlayerAdapter);
  Button stopButton(&aCdPlayerAdapter);

  aCdPlayerAdapter.setPlayButton(&playButton);
  aCdPlayerAdapter.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