728x90
반응형
01.메멘토 패턴 적용하기
- Client를 careTaker로쓰기
- memento역할이 중요 상태를 저장할것은
- GameSave로 클래스 생성
- 상태 정보가 바뀌면 안된다 그래서 final을 사용함
-
public final class GameSave { private final int blueTeamScore; private final int redTeamScore; public GameSave(int blueTeamScore, int redTeamScore) { this.blueTeamScore = blueTeamScore; this.redTeamScore = redTeamScore; } public int getBlueTeamScore() { return blueTeamScore; } public int getRedTeamScore() { return redTeamScore; } }
- GameSave로 클래스 생성
01.1 Game 코드 변경
- before
-
import java.io.Serializable; public class Game implements Serializable { private int redTeamScore; private int blueTeamScore; public int getRedTeamScore() { return redTeamScore; } public void setRedTeamScore(int redTeamScore) { this.redTeamScore = redTeamScore; } public int getBlueTeamScore() { return blueTeamScore; } public void setBlueTeamScore(int blueTeamScore) { this.blueTeamScore = blueTeamScore; } }
- after
- GameSave save()
- restore(GameSave gameSave) 추가
-
public class Game { private int redTeamScore; private int blueTeamScore; public int getRedTeamScore() { return redTeamScore; } public void setRedTeamScore(int redTeamScore) { this.redTeamScore = redTeamScore; } public int getBlueTeamScore() { return blueTeamScore; } public void setBlueTeamScore(int blueTeamScore) { this.blueTeamScore = blueTeamScore; } public GameSave save() { return new GameSave(this.blueTeamScore, this.redTeamScore); } public void restore(GameSave gameSave) { this.blueTeamScore = gameSave.getBlueTeamScore(); this.redTeamScore = gameSave.getRedTeamScore(); } }
01.2 Client 코드 변경
- before
-
public class Client { public static void main(String[] args) { Game game = new Game(); game.setRedTeamScore(10); game.setBlueTeamScore(20); int blueTeamScore = game.getBlueTeamScore(); int redTeamScore = game.getRedTeamScore(); Game restoredGame = new Game(); restoredGame.setBlueTeamScore(blueTeamScore); restoredGame.setRedTeamScore(redTeamScore); } }
- after
-
public class Client { public static void main(String[] args) { Game game = new Game(); game.setBlueTeamScore(10); game.setRedTeamScore(20); GameSave save = game.save(); game.setBlueTeamScore(12); game.setRedTeamScore(22); game.restore(save); System.out.println(game.getBlueTeamScore()); System.out.println(game.getRedTeamScore()); } }
728x90
반응형
'CS Study > 디자인패턴' 카테고리의 다른 글
2022-07-11-중재자패턴-1부-패턴소개 (0) | 2022.07.18 |
---|---|
2022-07-10-메멘토패턴-3부-장점과단점 (0) | 2022.07.18 |
2022-07-10-메멘토패턴-1부-패턴소개 (0) | 2022.07.18 |
2022-07-07-이터레이터패턴-3부-장점과단점 (0) | 2022.07.18 |
2022-07-07-이터레이터패턴-2부-패턴적용하기 (0) | 2022.07.18 |
댓글