Skip to content

Instantly share code, notes, and snippets.

@vitor-mariano
Last active June 24, 2017 01:10
Show Gist options
  • Save vitor-mariano/0c16eb01102523e377d2507d3a1ff53c to your computer and use it in GitHub Desktop.
Save vitor-mariano/0c16eb01102523e377d2507d3a1ff53c to your computer and use it in GitHub Desktop.
//
// main.cpp
// Watchman
//
// Created by Matheus Mariano on 21/06/17.
// Copyright © 2017 Matheus Mariano. All rights reserved.
//
#include <iostream>
#include <vector>
class Observer {
public:
virtual void handle() = 0;
};
class Subject {
std::vector<class Observer *> observers;
public:
void attach(Observer * observer) {
observers.push_back(observer);
}
void detach(int index) {
observers.erase(observers.begin() + index);
}
void notify() {
for (int index = 0; index < observers.size(); index++) {
observers.at(index)->handle();
}
}
};
class Board: public Subject {
};
class Led: public Observer {
unsigned int pin;
public:
Led(int p) {
pin = p;
}
void handle() {
std::cout << "New LED attached to pin " << pin << ".\n";
}
void on() {
std::cout << "Led at pin " << pin << " is on.\n";
}
void off() {
std::cout << "Led at pin " << pin << " is off.\n";
}
};
class AnalogInput: public Observer {
unsigned int pin;
public:
AnalogInput(int p) {
pin = p;
}
void handle() {
std::cout << "New AnalogPin attached to pin " << pin << ".\n";
}
int read() {
return 128;
}
};
int main() {
Board * board = new Board();
AnalogInput * photoCell = new AnalogInput(1);
Led * led = new Led(9);
// Setup
board->attach(photoCell);
board->attach(led);
board->notify();
// Loop
while (true) {
if (photoCell->read() > 50) {
led->on();
} else {
led->off();
}
}
return 0;
}
Copy link

ghost commented Jun 24, 2017

class Subject
{
typedef std::vector<class Observer*>::iterator Offset;

std::vector<class Observer *> observers;
Offset begin;
Offset end;

inline void update ()
{
	begin = observers.begin ();
	end = observers.end ();
}

public:
Subject ()
{
update ();
}

void attach (Observer * observer)
{
	observers.push_back (observer);
	update ();
}

void detach (unsigned int offset)
{
	if (offset >= end - begin)
		return;

	observers.erase (begin + offset);

	update ();
}

void notify ()
{
	for (unsigned int offset = 0; offset < end - begin; ++offset)
		(*(begin + offset))->handle ();
}

};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment