我正在嘗試使用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。
太簡單了,謝謝! – MihaiPopescu
有趣的是,現在我有一個崩潰:)微軟C++異常:在內存位置0x0032f6c4 std :: tr1 :: bad_weak_ptr .. – MihaiPopescu
我發現我必須創建一個[工廠](http://wiki.inkscape.org/ wiki/index.php/Boost_shared_pointers) – MihaiPopescu