원문: https://testing.googleblog.com/2009/02/with-all-sport-drug-scandals-of-late.html (Translated by Google Gemini)


최근의 모든 스포츠 약물 스캔들로 인해 요즘 좋은 롤 모델을 찾기가 어렵습니다. 하지만 롤 모델이 도메인 모델(비즈니스 엔티티의 객체 모델)이라면 MVP가 되기 위해 속임수를 쓸 필요가 없습니다. Model-View-Presenter를 사용하세요!

MVP는 MVC(Model-View-Controller)와 매우 유사합니다.

MVC에서는 아래 다이어그램과 같이 프레젠테이션 로직이 Controller와 View에 의해 공유됩니다. View는 일반적으로 가시적인 GUI 프레임워크 구성 요소에서 직접 파생되며, 모델을 관찰하고 사용자에게 시각적으로 보여줍니다. Controller는 사용자 이벤트를 모델 변경으로 변환하는 방법을 결정하는 역할을 합니다. MVP에서는 프레젠테이션 로직이 Presenter라고도 알려진 Supervising Controller에 의해 전적으로 처리됩니다.

MVC

mvc

MVP

mvp

View는 수동적이 되어 Presenter에 위임합니다.

public CongressionalHearingView() {
    testimonyWidget.addModifyListener(
        new ModifyListener() {
            public void modifyText(ModifyEvent e) {
                presenter.onModifyTestimony(); // presenter가 취할 행동을 결정
            }
        }
    );
}

Presenter는 Model에서 데이터를 가져와 View를 업데이트합니다.

public class CongressionalHearingPresenter {
    public void onModifyTestimony() {
        model.parseTestimony(view.getTestimonyText()); // 모델 조작
    }

    public void setWitness(Witness w) {
        view.setTestimonyText(w.getTestimony()); // 뷰 업데이트
    }
}

이러한 책임 분리를 통해 더 모듈화된 코드를 만들 수 있으며, Presenter와 View의 쉬운 단위 테스트를 가능하게 합니다.

public void testSetWitness() {
    spyView = new SpyCongressionalHearingView();
    presenter = new CongressionalHearingPresenter(spyView);
    presenter.setWitness(new Witness("Mark McGwire", "I didn't do it"));
    assertEquals("I didn't do it", spyView.getTestimonyText());
}

이는 완벽하게 합법적인 의존성 주입(Dependency Injection)을 사용합니다.