参考自定义容器的C++观察者模式
问题描述:
我有一个自定义容器(“主题”),它被许多其他类所观察。更换容器后,更改后将通知推送给所有观察员。例如,对于调整大小,处理流程看起来参考自定义容器的C++观察者模式
std::vector<double> vec;
void resize(size_t n)
{
vec.resize(n); //first resize
notify(Event::RESIZE); //afterwards inform observers about the resize event
}
现在,当我通过参考存取改变容器的元素,我看不出有什么明显的方法通知:当
double& operator[](size_t i)
{
notify(Event::CHANGE_ELEMENT); //no way to notify afterwards, so notify before
return vec[i];
}
因此我改变的元素作为
containerObject[2] = 1.1;
观察员得到了解的老态,这是通知后才更新。
是否有解决方法(除了使用setter方法)呢?
答
做一些辅助类,只是推销通知。
struct MyHelper
{
//This is may be a friend of your 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;
};
您可以在运营商这样做,那么:
MyHelper MyCustomContainer::operator[](size_t i)
{
MyHelper m(i, *this);
return m;
// MyHelper Destructor called
}
试试吧online!
我相信你的自定义容器不应该提供operator [](size_t)。可能是setter(),然后在应用更改后从setter发送通知。 – Jagannath 2014-10-31 23:05:49