我正在尝试使用 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;
};
我仍然有一个问题:如何从this指针中获取 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 接口,编译错误进一步上升。如果我尝试被动视图方法,情况也会一样。您可以在此处阅读有关它们的更多信息Model-View-Presenter Pattern。