2022-05-11-커맨드패턴-3부-장점과단점
본문 바로가기
CS Study/디자인패턴

2022-05-11-커맨드패턴-3부-장점과단점

by KyeongMin 2022. 5. 12.
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.단점

  • 커맨드 객체가 많이 늘어나고 복잡해 보일 수 있음

 

https://github.com/3DPIT/3dpit.github.io/blob/main/content/blog/DesignPattern/2022-05-11-%EC%BB%A4%EB%A7%A8%EB%93%9C%ED%8C%A8%ED%84%B4-3%EB%B6%80-%EC%9E%A5%EC%A0%90%EA%B3%BC%EB%8B%A8%EC%A0%90.md

 

GitHub - 3DPIT/3dpit.github.io

Contribute to 3DPIT/3dpit.github.io development by creating an account on GitHub.

github.com

 

728x90
반응형

댓글