Compare commits

...
4 Commits
Author SHA1 Message Date
portersky 5993dd1dc8 feat(cmat): Completed Ex61 Part 2 2026-10-08 10:16:23 +02:00
portersky 4e2e5f72a2 feat(cmat): Completed Ex61 Part 1 2026-10-08 10:08:48 +02:00
portersky 058179b643 feat(cmat): Completed Ex51 2026-10-07 15:13:55 +02:00
porterskyandQwen 3.8 27B a65e84e796 feat(cmat): pass hints to Ex42 observers
Extend the Ex42 observer pattern with Hint objects so each
observer receives the reason for the update instead of
querying the subject:

- Subject::notify() and Observer::update() now take a
  const Hint& argument.
- Add LightHint and WaitHint carrying the traffic light
  state and WAIT button state, defined in Pelican.h.
- Pole dispatches on hint type using dynamic_cast.
- The Pole constructor sets its initial lights directly
  from the Pelican's current state, since no notification
  is sent at startup. Stopgap until the initial update
  is handled properly.

Co-authored-by: Qwen 3.8 27B <qwen3.8_27b-q3_k_xl@lmstudio.local>
2026-10-07 11:31:16 +02:00
13 changed files with 517 additions and 469 deletions
+12 -10
View File
@@ -1,10 +1,12 @@
#ifndef OBSERVER_H #ifndef OBSERVER_H
#define OBSERVER_H #define OBSERVER_H
class Observer { class Hint;
public:
virtual void update() = 0; class Observer {
}; public:
virtual void update(const Hint&) = 0;
#endif };
#endif
+57 -55
View File
@@ -1,55 +1,57 @@
#include "Pelican.h" #include "Pelican.h"
#include "PelicanTimer.h" #include "PelicanTimer.h"
#include "Subject.h"
Pelican::Pelican() : pressed(false), RED_TIME(4), YELLOW_TIME(2), GREEN_TIME(3), FLASH_TIME(5), state(GREEN_IDLE) {
myTimer = new PelicanTimer(*this, &Pelican::timerExpired); Pelican::Pelican() : pressed(false), RED_TIME(4), YELLOW_TIME(2), GREEN_TIME(3), FLASH_TIME(5), state(GREEN_IDLE) {
} myTimer = new PelicanTimer(*this, &Pelican::timerExpired);
}
void Pelican::press(void) {
if (state == GREEN_IDLE) { void Pelican::press(void) {
state = YELLOW_STATE; if (state == GREEN_IDLE) {
myTimer->timeoutRequest(YELLOW_TIME); state = YELLOW_STATE;
pressed = true; myTimer->timeoutRequest(YELLOW_TIME);
notify(); pressed = true;
} else if (state != RED_STATE) { } else if (state != RED_STATE) {
pressed = true; pressed = true;
notify(); }
} notify(LightHint(state));
} notify(WaitHint(pressed));
}
void Pelican::timerExpired(void) {
switch (state) { void Pelican::timerExpired(void) {
case RED_STATE: switch (state) {
state = YELLOW_FLASHING; case RED_STATE:
myTimer->timeoutRequest(FLASH_TIME); state = YELLOW_FLASHING;
break; myTimer->timeoutRequest(FLASH_TIME);
break;
case YELLOW_FLASHING:
state = GREEN_TIMING; case YELLOW_FLASHING:
myTimer->timeoutRequest(GREEN_TIME); state = GREEN_TIMING;
break; myTimer->timeoutRequest(GREEN_TIME);
break;
case GREEN_TIMING:
if (pressed) { case GREEN_TIMING:
state = YELLOW_STATE; if (pressed) {
myTimer->timeoutRequest(YELLOW_TIME); state = YELLOW_STATE;
} else { myTimer->timeoutRequest(YELLOW_TIME);
state = GREEN_IDLE; } else {
} state = GREEN_IDLE;
break; }
break;
case GREEN_IDLE:
// should never happen case GREEN_IDLE:
break; // should never happen
break;
case YELLOW_STATE:
state = RED_STATE; case YELLOW_STATE:
pressed = false; state = RED_STATE;
myTimer->timeoutRequest(RED_TIME); pressed = false;
break; myTimer->timeoutRequest(RED_TIME);
} break;
}
notify();
} notify(LightHint(state));
notify(WaitHint(pressed));
}
+63 -51
View File
@@ -1,51 +1,63 @@
// ====================================================== // ======================================================
// //
// Represents a Pelican crossing // Represents a Pelican crossing
// //
// ====================================================== // ======================================================
#ifndef PELICAN_H #ifndef PELICAN_H
#define PELICAN_H #define PELICAN_H
#include "Subject.h" #include "Subject.h"
class PelicanTimer; class PelicanTimer;
class Pelican : public Subject { class Pelican : public Subject {
public: public:
Pelican(); Pelican();
// call when the WAIT button has been pressed // call when the WAIT button has been pressed
void press(void); void press(void);
// states that a Pelican can be in // states that a Pelican can be in
enum PelicanState { RED_STATE, YELLOW_FLASHING, GREEN_TIMING, GREEN_IDLE, YELLOW_STATE }; enum PelicanState { RED_STATE, YELLOW_FLASHING, GREEN_TIMING, GREEN_IDLE, YELLOW_STATE };
bool isPressed() const { return pressed; } bool isPressed() const { return pressed; }
PelicanState getState() const { return state; } PelicanState getState() const { return state; }
private: private:
// state that this Pelican is in // state that this Pelican is in
PelicanState state; PelicanState state;
// called by PelicanTimer when the lights need to change // called by PelicanTimer when the lights need to change
void timerExpired(void); void timerExpired(void);
const unsigned int RED_TIME; const unsigned int RED_TIME;
const unsigned int YELLOW_TIME; const unsigned int YELLOW_TIME;
const unsigned int GREEN_TIME; const unsigned int GREEN_TIME;
const unsigned int FLASH_TIME; const unsigned int FLASH_TIME;
// indicates whether the WAIT light should be on // indicates whether the WAIT light should be on
bool pressed; bool pressed;
// Timer that indicates when the lights should change // Timer that indicates when the lights should change
PelicanTimer *myTimer; PelicanTimer *myTimer;
private: private:
// prevent general use of copy ctor and operator= // prevent general use of copy ctor and operator=
Pelican(const Pelican &); Pelican(const Pelican &);
Pelican &operator=(const Pelican &); Pelican &operator=(const Pelican &);
}; };
#endif class LightHint : public Hint {
public:
LightHint(Pelican::PelicanState s) : state(s) { }
Pelican::PelicanState state;
};
class WaitHint : public Hint {
public:
WaitHint (bool p) : pressed(p) {}
bool pressed;
};
#endif
+80 -68
View File
@@ -1,68 +1,80 @@
#include "Pole.h" #include "Pole.h"
#include "Screen.h" #include "Pelican.h"
#include "Screen.h"
Pole::Pole(int x, int y, Pelican &p) : waitLight(new Light("WAIT", x + 6, y + 12, Screen::WHITE)), myPelican(p) {
myPelican.attach(*this); #include <typeinfo>
using namespace Screen; // we will discuss namespaces in the course Pole::Pole(int x, int y, Pelican &p) : waitLight(new Light("WAIT", x + 6, y + 12, Screen::WHITE)), myPelican(p) {
myPelican.attach(*this);
lights[RED_LIGHT] = new Light("*", x + 11, y + 3, RED);
lights[RED_MAN] = new Light("*<-=", x + 6, y + 4, RED); using namespace Screen; // we will discuss namespaces in the course
lights[YELLOW_LIGHT] = new Light("*", x + 11, y + 5, YELLOW);
lights[GREEN_LIGHT] = new Light("*", x + 11, y + 7, GREEN); lights[RED_LIGHT] = new Light("*", x + 11, y + 3, RED);
lights[GREEN_MAN] = new Light("*|-<", x + 6, y + 7, GREEN); lights[RED_MAN] = new Light("*<-=", x + 6, y + 4, RED);
lights[YELLOW_LIGHT] = new Light("*", x + 11, y + 5, YELLOW);
write(" _____ ", x, ++y, GRAY); lights[GREEN_LIGHT] = new Light("*", x + 11, y + 7, GREEN);
write(" /___ /| ", x, ++y, GRAY); lights[GREEN_MAN] = new Light("*|-<", x + 6, y + 7, GREEN);
write(" | | | ", x, ++y, GRAY);
write(" | |/| ", x, ++y, GRAY); write(" _____ ", x, ++y, GRAY);
write(" |____| | ", x, ++y, GRAY); write(" /___ /| ", x, ++y, GRAY);
write(" | |/| ", x, ++y, GRAY); write(" | | | ", x, ++y, GRAY);
write(" | | | ", x, ++y, GRAY); write(" | |/| ", x, ++y, GRAY);
write(" |____|/ ", x, ++y, GRAY); write(" |____| | ", x, ++y, GRAY);
write(" _||__ ", x, ++y, GRAY); write(" | |/| ", x, ++y, GRAY);
write(" /___ /| ", x, ++y, GRAY); write(" | | | ", x, ++y, GRAY);
write(" | | | ", x, ++y, GRAY); write(" |____|/ ", x, ++y, GRAY);
write(" | | | ", x, ++y, GRAY); write(" _||__ ", x, ++y, GRAY);
write(" |____|/ ", x, ++y, GRAY); write(" /___ /| ", x, ++y, GRAY);
write(" || ", x, ++y, GRAY); write(" | | | ", x, ++y, GRAY);
write(" || ", x, ++y, GRAY); write(" | | | ", x, ++y, GRAY);
write(" || ", x, ++y, GRAY); write(" |____|/ ", x, ++y, GRAY);
write(" || ", x, ++y, GRAY); write(" || ", x, ++y, GRAY);
write(" || ", x, ++y, GRAY); write(" || ", x, ++y, GRAY);
write(" || ", x, ++y, GRAY); write(" || ", x, ++y, GRAY);
write("========||===========", x, ++y, GRAY); write(" || ", x, ++y, GRAY);
write(" / || / ", x, ++y, GRAY); write(" || ", x, ++y, GRAY);
write("_ /_________ /_ ", x, ++y, GRAY); write(" || ", x, ++y, GRAY);
write("/ / ", x, ++y, GRAY); write("========||===========", x, ++y, GRAY);
write(" / || / ", x, ++y, GRAY);
update(); write("_ /_________ /_ ", x, ++y, GRAY);
} write("/ / ", x, ++y, GRAY);
Pole::~Pole() { setTrafficLights(myPelican.getState());
for (int i = 0; i < sizeof lights / sizeof(lights[0]); ++i) setWaitLight(myPelican.isPressed());
delete lights[i]; }
delete waitLight;
} Pole::~Pole() {
for (int i = 0; i < sizeof lights / sizeof(lights[0]); ++i)
void Pole::setTrafficLights(Pelican::PelicanState state) { delete lights[i];
static const Light::LightState LightStates[Pelican::YELLOW_STATE + 1][RED_MAN + 1] = { delete waitLight;
// red yellow green green man red man }
{Light::ON, Light::OFF, Light::OFF, Light::ON, Light::OFF}, // red
{Light::OFF, Light::FLASH, Light::OFF, Light::FLASH, Light::OFF}, // y flash void Pole::setTrafficLights(Pelican::PelicanState state) {
{Light::OFF, Light::OFF, Light::ON, Light::OFF, Light::ON}, // g time static const Light::LightState LightStates[Pelican::YELLOW_STATE + 1][RED_MAN + 1] = {
{Light::OFF, Light::OFF, Light::ON, Light::OFF, Light::ON}, // g idle // red yellow green green man red man
{Light::OFF, Light::ON, Light::OFF, Light::OFF, Light::ON} // yellow {Light::ON, Light::OFF, Light::OFF, Light::ON, Light::OFF}, // red
}; {Light::OFF, Light::FLASH, Light::OFF, Light::FLASH, Light::OFF}, // y flash
{Light::OFF, Light::OFF, Light::ON, Light::OFF, Light::ON}, // g time
for (int i = RED_LIGHT; i <= RED_MAN; i++) { {Light::OFF, Light::OFF, Light::ON, Light::OFF, Light::ON}, // g idle
lights[i]->set(LightStates[state][i]); {Light::OFF, Light::ON, Light::OFF, Light::OFF, Light::ON} // yellow
} };
}
for (int i = RED_LIGHT; i <= RED_MAN; i++) {
void Pole::setWaitLight(bool pressed) { waitLight->set(pressed ? Light::ON : Light::OFF); } lights[i]->set(LightStates[state][i]);
}
void Pole::update() { }
setTrafficLights(myPelican.getState());
setWaitLight(myPelican.isPressed()); void Pole::setWaitLight(bool pressed) { waitLight->set(pressed ? Light::ON : Light::OFF); }
}
void Pole::update(const Hint& hint) {
const WaitHint* waitHintPtr;
waitHintPtr = dynamic_cast<const WaitHint*>(&hint);
const LightHint* lightHintPtr;
lightHintPtr = dynamic_cast<const LightHint*>(&hint);
if (waitHintPtr != nullptr) {
setWaitLight(waitHintPtr->pressed);
}
if (lightHintPtr != nullptr) {
setTrafficLights(lightHintPtr->state);
}
}
+28 -28
View File
@@ -1,28 +1,28 @@
#ifndef POLE_H #ifndef POLE_H
#define POLE_H #define POLE_H
#include "Light.h" #include "Light.h"
#include "Observer.h" #include "Observer.h"
#include "Pelican.h" #include "Pelican.h"
class Pole : public Observer { class Pole : public Observer {
public: public:
Pole(int x, int y, Pelican &p); Pole(int x, int y, Pelican &p);
~Pole(); ~Pole();
void setTrafficLights(Pelican::PelicanState state); void setTrafficLights(Pelican::PelicanState state);
void setWaitLight(bool pressed); void setWaitLight(bool pressed);
void update(); void update(const Hint& hint);
private: private:
Pelican &myPelican; Pelican &myPelican;
enum LightName { RED_LIGHT, YELLOW_LIGHT, GREEN_LIGHT, GREEN_MAN, RED_MAN }; enum LightName { RED_LIGHT, YELLOW_LIGHT, GREEN_LIGHT, GREEN_MAN, RED_MAN };
Light *lights[RED_MAN + 1]; Light *lights[RED_MAN + 1];
Light *waitLight; Light *waitLight;
}; };
#endif #endif
+12 -12
View File
@@ -1,12 +1,12 @@
#include "Subject.h" #include "Subject.h"
#include "Observer.h" #include "Observer.h"
void Subject::attach(Observer &obs) { myObservers.insert(&obs); } void Subject::attach(Observer &obs) { myObservers.insert(&obs); }
void Subject::notify() const { void Subject::notify(const Hint& hint) const {
for (ObsList::const_iterator iter = myObservers.begin(); iter != myObservers.end(); ++iter) { for (ObsList::const_iterator iter = myObservers.begin(); iter != myObservers.end(); ++iter) {
(*iter)->update(); (*iter)->update(hint);
} }
} }
+25 -20
View File
@@ -1,20 +1,25 @@
#ifndef SUBJECT_H #ifndef SUBJECT_H
#define SUBJECT_H #define SUBJECT_H
class Observer; class Observer;
#include <set> #include <set>
class Subject { class Hint {
public: public:
typedef std::set<Observer *> ObsList; virtual ~Hint() = default;
void attach(Observer &obs); };
void notify() const;
class Subject {
private: public:
ObsList myObservers; typedef std::set<Observer *> ObsList;
}; void attach(Observer &obs);
void notify(const Hint&) const;
#endif
private:
ObsList myObservers;
};
#endif
+36 -24
View File
@@ -1,24 +1,36 @@
#include "TimerSet.h" #include "TimerSet.h"
#include "Timer.h" #include "Timer.h"
#include <iostream> #include <iostream>
#include <thread>
TimerSet::TimerSet() : previousTime(time(NULL)) {}
TimerSet::TimerSet() : previousTime(time(NULL)), pollingThread([this]{poll10Hz();}) {
void TimerSet::addATimer(Timer *t) { timers.push_back(t); } pollingThread.detach();
}
void TimerSet::pollAllTimers() {
std::time_t timeNow; void TimerSet::addATimer(Timer *t) { timers.push_back(t); }
if (time(&timeNow) > previousTime) {
previousTime = timeNow; void TimerSet::pollAllTimers() {
std::time_t timeNow;
for (auto it = timers.begin(); it != timers.end(); it++) { if (time(&timeNow) > previousTime) {
(*it)->tick(); previousTime = timeNow;
}
} for (auto it = timers.begin(); it != timers.end(); it++) {
} (*it)->tick();
}
TimerSet &TimerSet::Instance() { }
// Meyer's Singleton implementation }
static TimerSet pInstance;
return pInstance; TimerSet &TimerSet::Instance() {
} // Meyer's Singleton implementation
static TimerSet pInstance;
return pInstance;
}
void TimerSet::poll10Hz() {
using namespace std::chrono_literals;
while (true) {
auto const pause = 100ms;
pollAllTimers();
std::this_thread::sleep_for(pause);
}
}
+33 -29
View File
@@ -1,29 +1,33 @@
#ifndef TIMERSET_H #ifndef TIMERSET_H
#define TIMERSET_H #define TIMERSET_H
#include <ctime> #include <ctime>
#include <vector> #include <vector>
#include <thread>
class Timer;
class Timer;
class TimerSet {
public: class TimerSet {
void pollAllTimers(); public:
void addATimer(Timer *); void pollAllTimers();
void addATimer(Timer *);
private:
TimerSet(); private:
std::vector<Timer *> timers; TimerSet();
std::time_t previousTime; std::vector<Timer *> timers;
std::time_t previousTime;
// Meyer's singleton std::thread pollingThread;
public:
static TimerSet &Instance(); // Meyer's singleton
public:
private: static TimerSet &Instance();
// prevent copying and assignment of the singleton
TimerSet(const TimerSet &); private:
TimerSet &operator=(const TimerSet &); // prevent copying and assignment of the singleton
}; TimerSet(const TimerSet &);
TimerSet &operator=(const TimerSet &);
#endif
void poll10Hz();
};
#endif
+27 -32
View File
@@ -1,32 +1,27 @@
#include "Keyboard.h" #include "Keyboard.h"
#include "Pelican.h" #include "Pelican.h"
#include "Pole.h" #include "Pole.h"
#include "TimerSet.h" #include "TimerSet.h"
#include <cctype> // provides toupper() #include <cctype> // provides toupper()
int main() { int main() {
Keyboard kbd; Keyboard kbd;
Pelican thePelican; Pelican thePelican;
Pole pole1(20, 0, thePelican); Pole pole1(20, 0, thePelican);
Pole pole2(40, 0, thePelican); Pole pole2(40, 0, thePelican);
char c = 0; char c = 0;
while (std::toupper(c) != 'Q') { // loop until 'Q' is pressed while (std::toupper(c) != 'Q') { // loop until 'Q' is pressed
c = kbd.getChar(); // get the character
while (!kbd.isCharAvail()) { if (c == ' ') {
TimerSet::Instance().pollAllTimers(); // no key press to process, poll the timers // it's a space, so press the WAIT button
} thePelican.press();
}
c = kbd.getChar(); // get the character }
if (c == ' ') {
// it's a space, so press the WAIT button return 0;
thePelican.press(); }
}
}
return 0;
}
+44 -37
View File
@@ -1,37 +1,44 @@
#include "Person.h" #include "Person.h"
#include "PersonException.h" #include "PersonException.h"
#include "YoungPerson.h" #include "YoungPerson.h"
#include <iostream> #include <cstddef>
#include <iostream>
using std::cout; #include <memory>
Person::Person(std::string name, int age) : name(name), age(age) { using std::cout;
if (age < 0) {
throw PersonException("negative age"); std::shared_ptr<Person> Person::GetPerson(std::string name, int age) {
} if (age < 18) return std::make_shared<YoungPerson>(name, age);
return std::make_shared<Person>(name, age);
cout << "Person ctor\n"; }
Count++;
} Person::Person(std::string name, int age) : name(name), age(age) {
if (age < 0) {
Person::Person(const Person &) { throw PersonException("negative age");
cout << "Copy ctor\n"; }
Count++;
} cout << "Person ctor\n";
Count++;
Person::~Person() { }
cout << "Dtor\n";
Count--; Person::Person(const Person &) {
} cout << "Copy ctor\n";
Count++;
void Person::setSalary(int sal) { }
if (sal < 0) {
throw PersonException("negative salary"); Person::~Person() {
} cout << "Dtor\n";
Count--;
salary = sal; }
}
void Person::setSalary(int sal) {
int Person::GetCount() { return Count; } if (sal < 0) {
throw PersonException("negative salary");
int Person::Count = 0; }
salary = sal;
}
int Person::GetCount() { return Count; }
int Person::Count = 0;
+31 -28
View File
@@ -1,28 +1,31 @@
#ifndef Person_h #ifndef Person_h
#define Person_h #define Person_h
#include <string> #include <memory>
#include <string>
class Person {
public: class Person {
virtual ~Person(); public:
virtual ~Person();
static int GetCount();
static int GetCount();
Person(std::string name, int age);
Person(std::string name, int age);
void setSalary(int sal);
void setSalary(int sal);
private:
Person(const Person &); static std::shared_ptr<Person> GetPerson(std::string name, int age);
std::string name; private:
int age; Person(const Person &);
int salary;
std::string name;
static int Count; int age;
}; int salary;
#endif static int Count;
};
#endif
+69 -75
View File
@@ -1,75 +1,69 @@
#include <exception> #include <exception>
#include <string> #include <memory>
#include <vector> #include <string>
#include <vector>
#include "Person.h"
#include "Person.h"
#include "PersonException.h"
#include <iostream> #include "PersonException.h"
#include <iostream>
using std::cin;
using std::cout; using std::cin;
using std::string; using std::cout;
using std::exception; using std::string;
using std::exception;
int main() {
std::vector<Person *> people; int main() {
std::vector<std::shared_ptr<Person>> people;
string namePrompt = "Enter name: ";
string name; string namePrompt = "Enter name: ";
string agePrompt = "Enter age: "; string name;
int age; string agePrompt = "Enter age: ";
string salaryPrompt = "Enter salary: "; int age;
int salary; string salaryPrompt = "Enter salary: ";
int salary;
cout << namePrompt;
cin >> name; cout << namePrompt;
cin >> name;
while (name != "q") {
try { while (name != "q") {
cout << agePrompt; try {
cin >> age; cout << agePrompt;
cin >> age;
if (!cin) {
cin.clear(); if (!cin) {
string dummy; cin.clear();
cin >> dummy; string dummy;
throw PersonException("invalid age"); cin >> dummy;
} throw PersonException("invalid age");
}
Person *personPtr = new Person(name, age);
auto personPtr = Person::GetPerson(name, age);
cout << salaryPrompt;
cin >> salary; cout << salaryPrompt;
if (!cin) { cin >> salary;
cin.clear(); if (!cin) {
string dummy; cin.clear();
cin >> dummy; string dummy;
throw PersonException("invalid salary"); cin >> dummy;
} throw PersonException("invalid salary");
}
personPtr->setSalary(salary);
personPtr->setSalary(salary);
people.push_back(personPtr);
} people.push_back(personPtr);
}
catch (exception &e) {
cout << "PersonException thrown: " << e.what() << '\n'; catch (exception &e) {
} cout << "PersonException thrown: " << e.what() << '\n';
}
cout << "There are " << Person::GetCount() << " Person(s), " << people.size() << " in vector\n";
cout << "There are " << Person::GetCount() << " Person(s), " << people.size() << " in vector\n";
cout << namePrompt;
cin >> name; cout << namePrompt;
} cin >> name;
}
// delete all the person(s) in the vector
for (std::vector<Person *>::iterator iter = people.begin(); iter != people.end(); ++iter) { return 0;
delete *iter; }
}
cout << "There are " << Person::GetCount() << " Person(s) left dangling\n";
return 0;
}