etl::observer
This example shows an observable mouse driver that is observed by two event handlers.
#include <iostream>
#include "observer.h"
struct Position
{
int x;
int y;
};
struct Button
{
enum
{
Down,
Up
};
int state;
};
struct Wheel
{
int delta;
};
typedef etl::observer<const Position&, Button, Wheel> Mouse_Observer;
class Event_Handler1 : public Mouse_Observer
{
public:
void notification(const Position& position)
{
std::cout << "Event_Handler1 : Position = " << position.x << "," << position.y << "\n";
}
void notification(Button button)
{
std::cout << "Event_Handler1 : Button = " << ((button.state == Button::Up) ? "Up\n" : "Down\n");
}
void notification(Wheel wheel)
{
std::cout << "Event_Handler1 : Wheel delta = " << wheel.delta << "\n";
}
};
class Event_Handler2 : public Mouse_Observer
{
public:
void notification(const Position& position)
{
std::cout << "Event_Handler2 : Position = " << position.x << "," << position.y << "\n";
}
void notification(Button button)
{
std::cout << "Event_Handler2 : Button = " << ((button.state == Button::Up) ? "Up\n" : "Down\n");
}
void notification(Wheel wheel)
{
}
};
const int MAX_MOUSE_OBSERVERS = 2;
class Mouse_Driver : public etl::observable<Mouse_Observer, MAX_MOUSE_OBSERVERS>
{
public:
void Position_Event()
{
Position position = { 100, 200 };
notify_observers(position);
}
void Button_Event_Up()
{
Button button = { Button::Up };
notify_observers(button);
}
void Button_Event_Down()
{
Button button = { Button::Down };
notify_observers(button);
}
void Wheel_Event_Up()
{
Wheel wheel = { 50 };
notify_observers(wheel);
}
void Wheel_Event_Down()
{
Wheel wheel = { -25 };
notify_observers(wheel);
}
};
int main()
{
Mouse_Driver mouse_driver;
Event_Handler1 event_handler1;
Event_Handler2 event_handler2;
mouse_driver.add_observer(event_handler1);
mouse_driver.add_observer(event_handler2);
mouse_driver.Button_Event_Down();
mouse_driver.Button_Event_Up();
mouse_driver.Position_Event();
mouse_driver.Wheel_Event_Down();
mouse_driver.Wheel_Event_Up();
return 0;
}
Program output:-
Event_Handler1 : Button = Down
Event_Handler2 : Button = Down
Event_Handler1 : Button = Up
Event_Handler2 : Button = Up
Event_Handler1 : Position = 100,200
Event_Handler2 : Position = 100,200
Event_Handler1 : Wheel delta = -25
Event_Handler1 : Wheel delta = 50