Observer pattern help THANKS
Am I implementing it correctly? (used for a quiz application)
Observer.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#ifndef OBSERVER_H
#define OBSERVER_H
#include <vector>
class Observer
{
public:
virtual void update() = 0;
virtual ~Observer() {}
};
class Subject
{
private:
std::vector<Observer*> observers;
public:
virtual ~Subject() {}
void registerObserver(Observer* obs)
{
this->observers.push_back(obs);
}
void unregisterObserver(Observer* obs)
{
this->observers.erase(std::find(this->observers.begin(), this->observers.end(), obs));
}
void notify()
{
for (auto obs : this->observers)
{
obs->update();
}
}
};
#endif // OBSERVER_H
| |
QuizSession.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
#ifndef QUIZSESSION_H
#define QUIZSESSION_H
#include "Observer.h"
#include "Question.h"
//#include "FileManager.h"
#include <fstream>
#include <iostream>
#include <algorithm>
using std::ifstream;
using std::ofstream;
using std::endl;
using std::vector;
using std::sort;
class QuizSession : public Subject
{
public:
QuizSession() {
//FileManager::loadQuestions(this->questions);
ifstream f("/home/sysadmin/PracticPractice/questions");
int id;
string text;
string answer;
int score;
string delimiter;
while (f >> id && getline(f, delimiter, ';') && getline(f, text, ';') && getline(f, answer, ';') && f >> score) {
auto question = Question(id, text, answer, score);
questions.push_back(question);
}
f.close();
sortQuestions();
}
~QuizSession() {
//FileManager::writeQuestions(this->questions);
ofstream g("/home/sysadmin/PracticPractice/questions");
for (const auto &q : questions) {
g << q.getId() << ';' << q.getText() << ';' << q.getAnswer() << ';' << q.getScore() << endl;
}
g.close();
}
void addQuestion(Question &q) {
questions.push_back(q);
sortQuestions();
this->notify();
}
vector<Question> getQuestions() { return this->questions; }
// Descending by score
void sortQuestions() {
sort(questions.begin(), questions.end(), [&](const Question &q1, const Question &q2){
return q1.getScore() >= q2.getScore();
});
}
private:
vector<Question> questions;
};
#endif // QUIZSESSION_H
| |
Last edited on
Topic archived. No new replies allowed.