Solution: Observer Design Pattern
Get a detailed explanation of the solution to the observer pattern exercise.
We'll cover the following...
Solution
Press + to interact
#include <iostream>#include <list>#include <string>class Buyer {public:virtual ~Buyer(){};virtual void notify() = 0;};class Shop {public:void registerBuyer(Buyer* observer) {observers.push_back(observer);}void unregisterBuyer(Buyer* observer) {observers.remove(observer);}void notifyBuyers() {for (auto observer: observers) observer->notify();}private:std::list<Buyer *> observers;};class Directcustomer : public Buyer {public:Directcustomer(Shop& subject) : shop_obj(subject) {this->shop_obj.registerBuyer(this);}void notify() override {std::cout << "Dear customer, the product you requested is now back in stock \n";}private:Shop& shop_obj;};class Partnercustomer : public Buyer {public:Partnercustomer(Shop& subject) : shop_obj(subject) {this->shop_obj.registerBuyer(this);}void notify() override {std::cout << "Dear partner, the product you requested is now back in stock \n";}private:Shop& shop_obj;};int main() {Shop* subject = new Shop;Buyer* George = new Directcustomer(*subject);Buyer* Xyz_company = new Partnercustomer(*subject);subject->notifyBuyers();delete George;delete Xyz_company;delete subject;}
...