Skip to main content
deleted 27 characters in body; edited title
Source Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237

Is my perception of the observer Observer pattern correct?implementation

Reading head first design patternsI'm reading Head First Design Patterns and I'm currently reading about the observer pattern, is. Is what I produced what the observer pattern is all aboutcorrect?

Is my perception of the observer pattern correct?

Reading head first design patterns and I'm currently reading about the observer pattern, is what I produced what the observer pattern is all about?

Observer pattern implementation

I'm reading Head First Design Patterns and I'm currently reading about the observer pattern. Is what I produced correct?

Source Link

Is my perception of the observer pattern correct?

Reading head first design patterns and I'm currently reading about the observer pattern, is what I produced what the observer pattern is all about?

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

class ObserverInterface 
{
public:
    virtual void update(std::string message) = 0;
};

class concreteObserver : ObserverInterface 
{
    std::string name;
    std::string message;
public:
    concreteObserver(std::string name)
        :name(name)
    {}
    void update(std::string message)
    {
        this->message = message;

        std::cout << "Dear " << name << ", " << message << " from eBay" << std::endl;
    }
};

class SubjectInterface 
{
public:
    void subscribe(concreteObserver *subscriber)
    {
        subscribers.push_back(subscriber);
    }
    void unsubscribe(concreteObserver *subscriber)
    {
        subscribers.erase(std::remove(subscribers.begin(), subscribers.end(), subscriber), subscribers.end());
    }
    void notify(std::string message)
    {
        std::vector<concreteObserver*>::const_iterator itr = subscribers.begin();
        while (itr != subscribers.end())
        {
            (*itr)->update(message);
            ++itr;
        }
    }
private:
    std::vector<concreteObserver*> subscribers;
};

class concreteSubject : public SubjectInterface 
{
public:
    void newMessage(std::string msg)
    {
        notify(msg);
    }
};

int main(int argc, char* argv[])
{
    // EBAY
    concreteSubject ebay;

    // USERS
    concreteObserver user1("Steven");
    concreteObserver user2("John");

    // SUBSCRIBERS TO EBAY
    ebay.subscribe(&user1);
    ebay.subscribe(&user2);

    // EBAY SENDS NEW PROMOTIONS TO SUBSCRIBERS
    ebay.newMessage("enjoy free weekend listings");

    // UNSUBSCRIBE FROM EBAY
    ebay.unsubscribe(&user2);

    // EBAY SENDS NEW PROMOTION TO SUBSCRIBERS
    ebay.newMessage("free listings extended until 1st August");

    std::cout << std::endl << std::endl;
    system("pause");
    return 0;
}