开发者

STL implementation of MVP design pattern

开发者 https://www.devze.com 2023-04-01 21:33 出处:网络
I\'m trying to implement an MVP pattern using STL and I have used *shared_ptr* and *weak_ptr* for \"breaking the cycle\" when having recurrent references.

I'm trying to implement an MVP pattern using STL and I have used *shared_ptr* and *weak_ptr* for "breaking the cycle" when having recurrent references.

    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;
    };

Still I have one question: how can I get a shared_ptr out of a this pointer ? I saw the solution proposed by boost but sincerely think not going that far. The thing is that t开发者_StackOverflow中文版he only way to set a *weak_ptr* is from a shared_ptr and if I have to do this within a class that doesn't have a shared_ptr to itself, it's going to be hard.

So here basically the view creates the model but the model needs to reference back the view to implement the Observer pattern. The problem is that I'm stuck because I cannot set the weak_ptr view pointer for the model.

...
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>'
}
...

Is there any other way ? :) This is like saying that I don't trust the boost guys but it's not that. In fact, my question would be if there is another way to implement MVP without getting into this mess in the first place.

PS: I'm trying to implement the MVP Supervising Controller pattern. In the code sample I've excluded the i_presenter interface, the compiling error being further up. It would have been the same if I would have tried the Passive View approach. You can read more about them here Model-View-Presenter Pattern.


shared_from_this may help: http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/enable_shared_from_this.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号