我正在尝试使用 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?我看到了the solution proposed by boost但真诚地认为不会走那么远。问题是设置 *weak_ptr* 的唯一方法是来自 shared_ptr,如果我必须在一个本身没有 shared_ptr 的类中执行此操作,那将很难。
所以这里基本上是 View 创建模型,但模型需要引用回 View 以实现观察者模式。问题是我卡住了,因为我无法为模型设置 weak_ptr View 指针。
...
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 监督 Controller 模式。在代码示例中,我排除了 i_presenter 接口(interface),编译错误更进一步。如果我尝试被动 View 方法,结果会是一样的。您可以在这里阅读更多关于它们的信息 Model-View-Presenter Pattern .
最佳答案
shared_from_this
可能有帮助:http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/enable_shared_from_this.html
关于c++ - MVP设计模式的STL实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7250840/