Skip to content

Instantly share code, notes, and snippets.

@Leowbattle
Created April 11, 2018 11:22
Show Gist options
  • Save Leowbattle/03041e61349f321fcda7e4e7b47631ad to your computer and use it in GitHub Desktop.
Save Leowbattle/03041e61349f321fcda7e4e7b47631ad to your computer and use it in GitHub Desktop.
#include "Event.hpp"
void Event::doEvent() {
for (int i = 0; i < handlers.size(); i++) {
handlers.at(i)->handle(this);
}
if (!cancelled) {
execute();
}
}
bool Event::setCancelled(bool cancelled) {
bool cancellable = isCancellable();
if (cancellable) {
this->cancelled = cancelled;
}
return cancellable;
}
std::vector<std::shared_ptr<EventHandler>> Event::handlers;
void Event::addHandler(std::shared_ptr<EventHandler> handler) {
if (handlers.size() == 0) {
handlers.reserve(20);
}
handlers.emplace_back(handler);
}
#ifndef Event_hpp
#define Event_hpp
#include <vector>
#include <memory>
class Event;
class EventHandler {
public:
// Called upon Event::doEvent() call
virtual void handle(Event* event) = 0;
};
class Event {
public:
// The execute() and doEvent() functions are seperate so when the code creates
// an event it does not have to manually check if it is cancelled. It also
// means that the event can not ignore being cancelled.
virtual void doEvent();
// Method rather than variable so it can or can not be cancelled depending
// on various *things*
virtual bool isCancellable() = 0;
// Returns isCancellable()
virtual bool setCancelled(bool cancelled) final;
static void addHandler(std::shared_ptr<EventHandler> handler);
protected:
virtual void execute() = 0;
static std::vector<std::shared_ptr<EventHandler>> handlers;
private:
bool cancelled = false;
};
#endif /* Event_hpp */
#include "EventHello.hpp"
#include <iostream>
bool EventHello::isCancellable() {
return true;
}
// Won't be called if the event is cancelled
void EventHello::execute() {
std::cout << "Hello" << std::endl;
}
#ifndef EventHello_hpp
#define EventHello_hpp
#include "Event.hpp"
// Example implementation of Event
class EventHello: public Event {
public:
virtual bool isCancellable();
protected:
virtual void execute();
};
#endif /* EventHello_hpp */
#include <iostream>
#include "EventHello.hpp"
// Example implementation of EventHandler
class HelloHandler: public EventHandler {
public:
virtual void handle(Event* event) override {
//event->setCancelled(true);
std::cout << "I am the Globglogabgalab and I love books" << std::endl;
}
};
int main(int argc, const char * argv[]) {
EventHello::addHandler(std::make_shared<HelloHandler>(HelloHandler()));
EventHello e;
e.doEvent();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment