728x90
반응형
01.장점
- 기존의 코드 변경 없이 새로운 커맨드 만들 수 있음
- 변경에는 닫혀있고 확장에는 열려있음
- 수신자의 코드 즉, 게임이나 라이트 코드 바껴도 버튼이나 마이앱같은 요청하는 코드가 변경되지 않음
- 각각의 커맨드 자기 할일만 함
- 단일 책임원칙을 준수
- 커맨드 객체를 로깅, DB에 저장, 네트워크로 전송 하는 등 다양한 방법으로 활용할 수도 있음
01.1 undo 기능이 있다면?
- before
-
public interface Command{ void execute(); }
- after
-
public interface Command{ void execute(); void undo(); }
- before
-
public class GameEndCommand implements Command{ private Game game; public GameEndCommand(Game game){ this.game = game; } @Override public void execute(){ game.end(); } }
- after
-
public class GameEndCommand implements Command{ private Game game; public GameEndCommand(Game game){ this.game = game; } @Override public void execute(){ game.end(); } @Override public void undo(){ new GameStartcommand(this.game).excute(); } }
public class Button{
private Stack<Command> commands = new Stack<>();
public void press(){
command.execute();
commands.push(command);
}
public void undo(){
if(!command.isEmpty()){
Command command = commands.pop();
command.undo();
}
}
public static void main(String[] args){
Button button = new Button();
button.press(new GameStartCommand(new Game()));
button.press(new LightonCommand(new Light()));
button.undo();
button.undo();
}
}
02.단점
- 커맨드 객체가 많이 늘어나고 복잡해 보일 수 있음
728x90
반응형
'CS Study > 디자인패턴' 카테고리의 다른 글
2022-05-12-인터프리터패턴-2부-패턴적용하기 (0) | 2022.05.13 |
---|---|
2022-05-12-인터프리터패턴-1부-패턴소개 (0) | 2022.05.12 |
2022-05-11-커맨드패턴-2부-패턴적용하기 (0) | 2022.05.12 |
2022-05-11-커맨드패턴-1부-패턴소개 (0) | 2022.05.12 |
22-04-18-책임연쇄패턴-4부-장점과단점 (0) | 2022.04.18 |
댓글