Observer Pattern - How to handle unexpected changes? -


what kind of mechanism used update object... unless checking has changed , instruct subject/observed push state...

what mean instance object changes state, how should handle change, should mark changed, how let observers know has changed without having checking if object observing has changed or not... how handle unexpected changes , eliminate them our notifications?

there whole callback thing, event listeners, etc... use don't understand, use black box, know bit more internals of such mechanisms.

there lot of different mechanisms track changes of object.

the first alternative use indeed observers. implies every method changes data in object, calls observers. in practice it's best put in 1 function, this:

class myclass    {    public:       void setvalue(int value)          {          m_value = value;          notifyobservers();          }    private:       void notifyobservers()          {          (auto it=m_observers.begin();it!=m_observers.end();++it)             (*it)->notify(this);          }       std::list<observer *> m_observers;    }; 

an alternative store whether object has been changed. however, requires define meaning of "has been changed"; in other words: when reset 'changed' flag. easy solution use version number. whenever object changes, increase version number, this:

class myclass    {    public:       void setvalue(int value)          {          m_value = value;          ++m_version;          }       int getversion() const          {          return m_version;          }    private:       int m_version;    }; 

now other classes can request version number , use see whether has been changed since last asked version number.

both approaches have advantages , disadvantages:

  • in observer mechanism, changes can slow (since need call observers), guaranteed observers up-ot-date
  • in version-number approach, changes fast, rely on other classes regularly query class changes

which mechanism best in case depends on situation. if found in practice it's best mix them, depending on situation. changes best propagated (e.g. in calculations), other changes best delayed (e.g. updating screen).


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -