들어가며...

MVC 구조가 무엇이고 어떻게 적용되는 지 알아보려한다. 또한, MVC를 적용하지 않은 코드를 MVC 형태로 바꿔 보려고 한다. 내가 작성한 코드고 주관적인 의견이므로 정답이 아닐 수 있다.

MVC 패턴이란

MVC(Model-View-Controller) 패턴에서 Controller는 Model의 데이터를 조회하거나 업데이트하는 역할을 한다. Model이 업데이트 되면, View는 화면이 반영한다.

MVC 패턴으로 변경

우선 내가 작성한 코드의 요구 사항이다.

BridegeGame -> Bridge -> InputView, OutputView

처음 내가 작성한 코드에 MVC 패턴을 빗대어 본 모습이다. MVC 패턴을 생각하고 만든 코드가 아니기 때문에 몇 가지 문제점이 존재한다고 판단하였다.

😵 문제점

App.js

const model = new Model();
const Controller = new Controller();

View.readBridgeSize(bridge, bridgeGame);

View에 Model과 Controller을 넣어주고 View에서 모든 것을 처리하도록 해주었다. 내부적으로는 Controller가 Model을 처리하지만 App에서 보기에 MVC 패턴 역할이 맞지 않아 보인다.

Controller(BridgeGame)

class BridgeGame {
  constructor() {
    this.round = 0;
    this.crossing = true;
    this.success = false;
    this.attempt = 1;
    this.upResult = [];
    this.downResult = [];
  }

Controller 부분인 BridgeGame이다. 생성자 이름을 보면 success, attempt, result 와 같이 Model을 업데이트하는데 전혀 관련이 없고 게임 결과에 대한 데이터 같다.

upMovement(bridge, round) {
    if (bridgeUD[round] === "U") {
    this.upResult[round] = " O ";
    this.downResult[round] = "   ";
  } else {
    this.upResult[round] = " X ";
    this.downResult[round] = "   ";
    this.setCross(false);
  }
}

BridgeGame에서 upMovement 함수이다. 사용자가 다리 위 칸을 건너겠다는 "U"라는 입력을 주었을 때 일어나는 일에 대한 함수이다. 답이 맞으면 [ O ] 답이 틀리면 [ X ]를 결과에 push 해준다.

Controller는 Model의 데이터를 업데이트하는 역할이 주 업무인데, 자기 자신의 데이터를 업데이트 있다. BridgeGame의 생성자 모두 Model로 보내주는 것이 좋을 것 같다.

View(OutputView)

  printResult(bridgeGame) {
    MissionUtils.Console.print("최종 게임 결과");
    this.printMap(bridgeGame.getUpResult(), bridgeGame.getDownResult());
    MissionUtils.Console.print(
      `게임 성공 여부: ${(bridgeGame.getSuccess() && "성공") || "실패"}`
    );
    MissionUtils.Console.print(`총 시도한 횟수: ${bridgeGame.getAttempt()}`);
    MissionUtils.Console.close();
  }

OutputView에서 printResult를 보면 마찬가지로 Controller의 부분이 출력 화면에 보여지고 있다. Model이 업데이트되면 화면에 보여주는 것이 View니까, Model의 데이터가 출력 화면에 보여지면 좋을 것 같다.

😊 바꿔보기

App.js

const model = new Model();
const view = new View(model);

new Controller(view, model);

View는 Model을 보여주고 Controller는 Model을 업데이트 해준다. MVC 패턴에 좀 더 어울리게 바꿔보았다.

Model(Result.js)

class Result {
  constructor() {
    this.success = false;
    this.attempt = 1;
    this.upResult = [];
    this.downResult = [];
  }

Result Model을 생성해 결과 부분을 데이터로 넣어주었다. Bridge와 Result를 모델로 묶는 것도 하나의 방법일 것 같다.

Controller(BridgeGame.js)

upMovement(bridge, result, round) {
    if (bridgeUD[round] === "U") {
    result.upResult[round] = " O ";
    result.downResult[round] = "   ";
  } else {
    result.upResult[round] = " X ";
    result.downResult[round] = "   ";
    this.setCross(false);
  }
}

Controller 부분에서 Result Model을 넣어주고 결과를 업데이트하는 함수를 불러온다.

+ Recent posts