我正在尝试使用STL实现MVP模式,我使用了*shared_ptr*和*weak_ptr*来"打破循环",当有循环引用时。
class i_model;
class i_view;
class i_view
{
public:
i_view() : myModel(NULL) {}
virtual ~i_view() {}
void set_model(const std::shared_ptr<i_model>& _model) { myModel = _model; }
virtual void fire_keyboard(unsigned char key, int x, int y) {}
virtual void on_model_changed() { };
virtual void render() const = 0;
protected:
std::shared_ptr<i_model> myModel;
};
class i_model
{
public:
i_model() : myView() {}
virtual ~i_model() {}
void set_view(const std::shared_ptr<i_view>& _view) { myView = _view; }
void fire_model_changed() { std::tr1::shared_ptr<i_view> p = myView.lock(); p->on_model_changed(); }
protected:
std::weak_ptr<i_view> myView;
};
我还有一个问题:我怎么能得到一个shared_ptr的这个指针?我看到了boost提出的解决方案,但我真心认为不要走得太远。问题是,设置*weak_ptr*的唯一方法是从shared_ptr,如果我必须在一个本身没有shared_ptr的类中这样做,这将是困难的。
这里视图创建了模型但是模型需要引用视图来实现观察者模式。问题是,我卡住了,因为我不能为模型设置weak_ptr视图指针。
...
void MyView::Create()
{
std::shared_ptr<MyModel> model = std::make_shared<MyModel>();
i_view::set_model(model);
model->set_view(this); // error C2664: cannot convert parameter 1 from MyModel* to 'std::tr1::shared_ptr<_Ty>'
}
...
还有别的办法吗?这就像说我不相信这些家伙,但事实并非如此。事实上,我的问题是,是否有另一种方法来实现MVP,而不会首先陷入这种混乱。
PS:我正试图实现MVP监督控制器模式。在代码示例中,我已经排除了i_presenter接口,这样编译错误就更严重了。如果我尝试了被动视图方法,结果也是一样的。你可以在这里阅读更多关于模型-视图-演示器模式的信息。
shared_from_this
可能有所帮助:http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/enable_shared_from_this.html