Last active
June 24, 2017 01:10
-
-
Save vitor-mariano/0c16eb01102523e377d2507d3a1ff53c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
class Subject
{
typedef std::vector<class Observer*>::iterator Offset;
public:
Subject ()
{
update ();
}
};