Skip to content

Instantly share code, notes, and snippets.

@BeautyfullCastle
Created January 8, 2022 08:10
Show Gist options
  • Save BeautyfullCastle/d8957e1073cb08a9e5fca8842896e246 to your computer and use it in GitHub Desktop.
Save BeautyfullCastle/d8957e1073cb08a9e5fca8842896e246 to your computer and use it in GitHub Desktop.
C++ Observer Pattern Example (Easy and simple to understand)
#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;
}
#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);
}
#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);
};
#include "Subject.h"
Subject::Subject(Observer observer)
{
this->observer = observer;
}
void Subject::setName(string name)
{
this->name = name;
observer.invoke(this->name);
}
#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