samedi 30 juin 2018

When apply observer pattern an error occured

I have the following code:

class ISubscriber;
class News {
public:
    float getVersion() { return this->version; }
    void setVersion(float state) { this->version= state; this->notifyAllSubscribers(); }
    void attach(ISubscriber *observer) { this->subscribers.push_back(observer); }
    void notifyAllSubscribers() {
        for (vector<ISubscriber*>::iterator it = subscribers.begin(); it != subscribers.end(); it++){
            (*(*it)).update();
        }
    }
private:
    vector<ISubscriber*> subscribers;
    float version;
};

class ISubscriber {
public:
    News *news;
    virtual void update() = 0;
};

class Subscriber1 : public ISubscriber {
public:
    Subscriber1(News *news) { this->news = news; this->news->attach(this); }
    void update() override { cout << "Subscriber1: A new version of the newspaper has been launched (v" << this->news->getVersion() << ")" << endl; }

};

class Subscriber2 : public ISubscriber {
public:
    Subscriber2(News *news) { this->news = news; this->news->attach(this); }
    void update() override { cout << "Subscriber2: A new version of the newspaper has been launched (v" << this->news->getVersion() << ")" << endl; }

};


int main(int argc, char *argv[]) {
    News newspaper;
    newspaper.setVersion(2.1f);

    Subscriber1 sb1(&newspaper);
    Subscriber2 sb2(&newspaper);
    return 0;
}

But a strange errors happened:

The first error points to this code (*(*it)).update(); in news class. Why that errors happened, what's the reason?

Aucun commentaire:

Enregistrer un commentaire