Created
January 8, 2022 08:10
-
-
Save BeautyfullCastle/d8957e1073cb08a9e5fca8842896e246 to your computer and use it in GitHub Desktop.
C++ Observer Pattern Example (Easy and simple to understand)
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
#include <iostream> | |
#include <string> | |
#include "Subject.h" | |
#include "Observer.h" | |
void onChange(string name); | |
void main() | |
{ | |
Observer ob(onChange); | |
Subject sub(ob); | |
sub.setName("Gray"); | |
sub.setName("Kevin"); | |
} | |
void onChange(string name) | |
{ | |
cout << "My name is changed to " << name << "." << endl; | |
} |
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
#include "Observer.h" | |
Observer::Observer() : function(nullptr) | |
{ | |
} | |
Observer::~Observer() | |
{ | |
function = nullptr; | |
} | |
Observer::Observer(void(*function)(string)) | |
{ | |
this->function = function; | |
} | |
void Observer::invoke(string str) | |
{ | |
function(str); | |
} |
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
#pragma once | |
#include <string> | |
using namespace std; | |
class Observer | |
{ | |
public: | |
Observer(); | |
~Observer(); | |
public: | |
Observer(void(*function)(string)); | |
void invoke(string str); | |
private: | |
void(*function)(string); | |
}; |
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
#include "Subject.h" | |
Subject::Subject(Observer observer) | |
{ | |
this->observer = observer; | |
} | |
void Subject::setName(string name) | |
{ | |
this->name = name; | |
observer.invoke(this->name); | |
} |
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
#pragma once | |
#include "Observer.h" | |
class Subject | |
{ | |
public: | |
Subject(Observer observer); | |
void setName(string name); | |
private: | |
Observer observer; | |
string name; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment