2011-08-30 3 views
1

STL을 사용하여 MVP 패턴을 구현하려고하는데 반복 참조가있을 때 * cycle_ breaking * 및 * weak_ptr *을 사용했습니다. MVP 디자인 패턴의 STL 구현

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

아직도 나는 1 개 개의 질문이 있습니다 : 어떻게 포인터 밖으로 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를 구현하는 또 다른 방법이 있다면 것입니다.

추신 : 저는 MVP 감독 컨트롤러 패턴을 구현하려고합니다. 코드 샘플에서 i_presenter 인터페이스를 제외 시켰습니다. 컴파일 오류가 발생했습니다. Passive View 방식을 시도해 본다면 동일했을 것입니다. 여기에 대한 자세한 내용은 Model-View-Presenter Pattern을 참조하십시오.

답변

2
+0

그것은, 덕분에 너무 간단했다! – MihaiPopescu

+0

흥미 롭군요, 지금은 충돌이 있습니다.) Microsoft C++ 예외 : 메모리 위치 0x0032f6c4의 std :: tr1 :: bad_weak_ptr .. – MihaiPopescu

+0

[공장] (http://wiki.inkscape.org/)을 만들어야합니다. 위키/index.php/Boost_shared_pointers) – MihaiPopescu

관련 문제