커맨드 Command
🙈

커맨드 Command

Created
Apr 25, 2024 04:17 AM
Last edited time
Last updated April 25, 2024
Tags
CS
Language
URL

Intro::

디자인 패턴 중 행위패턴인 커맨드에 대해 알아봅시다.
 

커맨드 패턴이란?

💡
커맨드(Command) 패턴은 행위 디자인 패턴 중 하나로, 요청 자체를 캡슐화하여 요청을 발생시키는 객체와 요청을 수행하는 객체를 분리하는 데 사용됩니다. 이 패턴을 통해 명령을 객체로 캡슐화함으로써, 명령의 발행과 수행을 분리하여 시스템의 유연성과 확장성을 크게 향상시킵니다.
 

장점

  1. 분리와 확장성: 커맨드 패턴은 요청을 발생시키는 부분과 요청을 수행하는 부분을 분리하여 서로의 독립성과 확장성을 증가시킵니다.
  1. 재사용성과 조합: 커맨드 객체를 재사용하고, 조합하여 복잡한 명령을 만들 수 있습니다.
  1. 유연한 제어: 명령의 실행을 스케쥴링하거나, 로그를 남기고, 취소 및 재실행 같은 작업을 용이하게 수행할 수 있습니다.

단점

  1. 클래스의 증가: 각각의 개별 명령마다 커맨드 클래스를 생성해야 하므로, 시스템의 복잡도가 증가할 수 있습니다.
  1. 구현의 복잡성: 커맨드 패턴을 적용하면 초기 설계와 구현이 복잡해질 수 있습니다.

코드 예시

// 커맨드 인터페이스 interface Command { void execute(); } // 리시버 클래스 class Light { public void on() { System.out.println("Light is on!"); } public void off() { System.out.println("Light is off!"); } } // 구체적인 커맨드 클래스 class LightOnCommand implements Command { private Light light; public LightOnCommand(Light light) { this.light = light; } @Override public void execute() { light.on(); } } class LightOffCommand implements Command { private Light light; public LightOffCommand(Light light) { this.light = light; } @Override public void execute() { light.off(); } } // 인보커 클래스 class RemoteControl { private Command command; public void setCommand(Command command) { this.command = command; } public void pressButton() { command.execute(); } } // 메인 클래스 public class Main { public static void main(String[] args) { Light light = new Light(); Command lightsOn = new LightOnCommand(light); Command lightsOff = new LightOffCommand(light); RemoteControl remote = new RemoteControl(); remote.setCommand(lightsOn); remote.pressButton(); remote.setCommand(lightsOff); remote.pressButton(); } }
 
 

References::

Loading Comments...