C++ observer pattern with reference to custom container -
C++ observer pattern with reference to custom container -
i have custom container (the "subject") observed many other classes. upon alter of container, notification pushed observers after alter made. e.g., resize, process flow looks as
std::vector<double> vec; void resize(size_t n) { vec.resize(n); //first resize notify(event::resize); //afterwards inform observers resize event } now, when alter elements of container via reference access, see no obvious way notification:
double& operator[](size_t i) { notify(event::change_element); //no way notify afterwards, notify before homecoming vec[i]; } thus when alter element as
containerobject[2] = 1.1; the observers informed old state, updated after notification.
is there workaround (other using setter method) this?
make kind of helper class, wich pushes notification on destruction.
struct myhelper { //this may friend of container myhelper(std::size_t index, mycustomcontainer& ref) : _index(index), _ref(ref) { } ~myhelper() { notify(event::change_element); } double& operator=(double rhs) { _ref._vec[_index] = rhs; } private: std::size_t _index; mycustomcontainer _ref; }; you can in operator then:
myhelper mycustomcontainer::operator[](size_t i) { myhelper m(i, *this); homecoming m; // myhelper destructor called } try online!
c++ observer-pattern
Comments
Post a Comment