(유니티) MVP

티원·2025년 11월 10일

디자인패턴

목록 보기
9/16

MVP
model view presenter

View에서 Presenter의 생성자를 이용해서 사용, 인터페이스 사용
MVP2 (추가 예제 코드 -> 잘모르겠으면 확인해보기)

코드

  1. Model
public class PlayerMVPModel
{
    //로직 코드
    private int health = 100;
    public int Health => health;
    public event Action<int> OnHealthChanged;

    public void TakeDamage(int amount)
    {
        health -= amount;
        OnHealthChanged?.Invoke(health);
    }
}
  1. 인터페이스
public interface IPlayerMVPView
{
    public void UpdateHealthUI(int health);
}
  1. Presenter
public class PlayerMVPPresenter
{
    private PlayerMVPModel _model;
    private IPlayerMVPView _playerView;
    
    public PlayerMVPPresenter(PlayerMVPModel model, IPlayerMVPView view)
    {
        _model = model;
        _playerView = view;
        _model.OnHealthChanged += _playerView.UpdateHealthUI;
    }

    public void UpdateHPTakeDamage()
    {
        _model.TakeDamage(10);
    }

}
  1. View
public class PlayerMVPView : MonoBehaviour, IPlayerMVPView
{
    //UI 코드
    [SerializeField] private TextMeshProUGUI healthText;
    private PlayerMVPPresenter playerMVPPresenter;
    InputAction damageAction;
    private void Awake()
    {
        damageAction = InputSystem.actions.FindAction("Attack");
    }
    private void Start()
    {
        PlayerMVPModel model = new PlayerMVPModel();
        playerMVPPresenter = new PlayerMVPPresenter(model,this);
        Debug.Log("Start");
    }

    private void OnEnable()
    {
        damageAction.performed += OnAttack;
    }
    private void OnDisable()
    {
        damageAction.performed -= OnAttack;
    }

    private void OnAttack(InputAction.CallbackContext ctx)
    {
        Debug.Log("Att");
        playerMVPPresenter.UpdateHPTakeDamage();
    }

    public void UpdateHealthUI(int health)
    {
        Debug.Log("dd");
        healthText.text = health.ToString();
    }
}

Player에다가 View 스크립트를 넣음
만약 UIManager가 있는 구조라면 View 스크립트에 UIManger.SetText(); 로 접근하기

MVC 와 MVP의 차이점

MVP에서는 뷰 1개 = 프레젠터 1개
MVC에서는 컨트롤러가 여러 뷰를 관리할 수 있다.

MVP는 입력처리를 View서 받고, 프레젠터가 그 입력을 처리하여 전달
MVC는 입력처리를 Controller에서
그래서 일반적으로 MVC모델보다 MVP모델이 더 결합도가 낮다.
또 MVC에서는 뷰가 모델을 구독하는 등의 동작이 가능하지만 MVP에서는 모델과 뷰 사이의 전달을 프레젠터가 온전히 담당

(추가사항) 입력처리가 많다면 따로 입력처리를 하는 스크립트를 빼도 될듯. view는 보이는거만 처리되도록

왜 쓰는가?

  • UI와 로직을 분리하여 유지보수 및 테스트 용이성을 높이기 위해 사용
  • 테스트용이성? : Model의 코드에 TakeDamage(10); 이런식으로 가짜 데이터를 넘겨줘서 동작이 어떻게 진행될지 테스트를 해볼 수 있다

후기

인터넷에 너무 많은 정보가 있어서 정리가 오래걸렸다
꼭 인터페이스를 쓰지 않아도 되는 것 같은데... 일단은 이렇게 사용
MVC보다는 난이도가 있는 편이다

MVP2 (추가 예제 코드 -> 잘모르겠으면 확인해보기)

0개의 댓글