Callbacks in C++


external polymorphism

//----------------------------------------
// library code
//----------------------------------------
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;
};
//----------------------------------------
// optionally library 
// or clientcode
//----------------------------------------
template <class T>
class ExternalPolymorph:
  public ButtonClient
{
public:
  ExternalPolymorph(T* pT_):_pT(pT_){}
  /*virtual*/ void buttonPushed(Button* pButton_) 
  {_pT->myButtonPushed(pButton_);}
private:
  T* _pT;
};
//----------------------------------------
// client code
//----------------------------------------
#include <iostream.h>
class CdPlayer
{
public:
  void myButtonPushed(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;
  ExternalPolymorph<CdPlayer> anExternalPolymorph(&aCdPlayer);

  Button playButton(&anExternalPolymorph);
  Button stopButton(&anExternalPolymorph);

  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