Answer the question
In order to leave comments, you need to log in
Is the Observer pattern implemented correctly?
Hello, help me understand how the Observer pattern should look like, they write differently everywhere, everyone has different diagrams, what is missing in my implementation or maybe something extra?
My implementation (maybe if in the error code please tell me where it is incorrect):
class Observer;
class Subject {
public:
virtual ~Subject() {};
virtual void attach(Observer* follower) {
followers.push_back(follower);
}
virtual void detach(int index) {
followers.erase(followers.begin() + index);
}
virtual void Notify() {
for (int i = 0; i < followers.size(); ++i) {
}
}
private:
std::vector<Observer*> followers;
};
class ConcreteSubject : public Subject {
public:
int GetState() {
return SubjectState;
}
void SetState(int NewSubjectState) {
SubjectState = NewSubjectState;
}
private:
int SubjectState;
};
class Observer {
public:
virtual ~Observer() {};
virtual void Update() = 0;
};
class ConcreteObserver : public Observer {
public:
ConcreteObserver(ConcreteSubject* subject_to_follow) {
FollowedSubject = subject_to_follow;
FollowedSubject->attach(this);
}
void Update() {
ObserverState = FollowedSubject->GetState();
}
private:
ConcreteSubject* FollowedSubject;
int ObserverState;
};
Answer the question
In order to leave comments, you need to log in
One line left to add...
virtual void Notify() {
for (int i = 0; i < followers.size(); ++i) {
followers[i].Update();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question