2011-08-30 93 views
1

我正在尝试使用STL实现MVP模式,并且在重复引用时我使用* shared_ptr *和* weak_ptr *作为“打破循环”。STP MVP设计模式的实现

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了这个指针?我看到了the solution proposed by 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

回答