jeudi 30 septembre 2021

C++ : Observer Pattern

How efficiently can I write setScore() without adding it to IObserver ? Is there any better to add such method ? or any better implementation than this ? PLEASE HELP.

ObserverPattern.cpp:88:7: error: ‘class IObservable’ has no member named ‘setScore’

//interface
class IObserver
{
public:
    virtual void update(int) = 0;   
};

//interface
class IObservable
{
public:
    virtual void subscribe(IObserver *) = 0;
    virtual void unsubscribe(IObserver *) = 0;
    virtual void notifyAll() = 0;   
};


class CricketMatchScore : public IObservable
{
    
public:

    CricketMatchScore()
    :   mScore (0)
    {

    }

    void subscribe(IObserver * obj)
    {
        mObservers.push_back(obj);
    }   

    virtual void unsubscribe(IObserver * obj)
    {
        auto iter = std::find(mObservers.begin(), mObservers.end(), obj);
        if (iter != mObservers.end())
        {
            mObservers.erase(iter);
        }
    }

    void notifyAll()
    {
        for (auto & item : mObservers)
        {
            item->update(mScore);
        }
    }

    void virtual setScore(int score)
    {
        if (mScore != score)
        {
            mScore = score;
            notifyAll();
        }
    }

private:
    std::vector<IObserver*> mObservers;
    int mScore;

};


class CricInfo : public IObserver
{
public:
    void update(int score)
    {
        std::cout<<score<<std::endl;
    }
};

int main()
{
    IObserver * ob1 = new CricInfo;
    IObserver * ob2 = new CricInfo;

    IObservable * obl = new CricketMatchScore;

    obl->subscribe(ob1);
    obl->subscribe(ob2);

    obl->setScore(20);

    return 0;

}

Aucun commentaire:

Enregistrer un commentaire