본문 바로가기

강의/Design pattern

커맨드(Command) 패턴

SMALL

Command Pattern

요청 호출과 처리를 분리하는 패턴 중 하나이고, 중간에 Command 객체를 사용한다
요청을 처리하는 방법이 바뀌어도, 호출자의 코드는 변경되지 않는다. 요청을 캡슐화하여 전달한다.


Code Example

Button

public class Button {
	private Light light;
	public Button(Light light) {
		this.light = light;
	}

	public void press() {
		light.on();
	}
	public static void main(String[] args) {
		Button button = new Button(new Light());
		button.press();
		button.press();
		button.press();
		button.press();
	}
}

MyApp

public class MyApp {
	private Light light;
	public Button(Light light) {
		this.light = light;
	}

	public void press() {
		light.on();
	}
}

Code Example - 2

Command

public interface Command {
	void execute();
}

Button

public class Button {
	private Command command;
	public Button (Command command) {
		this.command = command;
	}
	public void press() {
		command.execute();
	}
	public static void main(String[] args) {
		Button button = new Button({
			@Override
			public void execute() {
				
			}
		});
		button.press();
		button.press();
	}
}

LightOnCommand

public class LightOnCommand implements Command {
	private Light light;

	@Override
	public void execute() {
		light.on();
	}
}

Button의 코드는 변경되지 않는다. 변경 사항이 있을 경우 Command의 내용만 변경되어 범위가 축소되는 효과를 볼 수 있다.


장단점

장점

  • 기존 코드를 변경하지 않고 새로운 커맨드를 만들 수 있다.
  • 수신자의 코드가 변경되어도 호출자의 코드는 변경되지 않는다.
  • 커맨드 객체를 로깅, DB 저장, 네트워크로 전송 등 다양한 방법으로 활용이 가능하다.

단점

  • 코드가 복잡하고 클래스가 많아진다.

Example

SimpleJdbcInsert

insert query를 실행하는데 필요한 모든 정보를 가지는 Command Object이다.

public void add(Command command) {
	SimpleJdbcInsert insert = new SimpleJdbcInsert(dataSource)
		.withTableName("command")
		.usingGenerateKeyColumns("idx");
}

SimpleJdbcCall

JDBC의 프로시저를 호출하는데 필요한 일종의 커맨드 객체이다.

SMALL

'강의 > Design pattern' 카테고리의 다른 글

이터레이터(Iterator) 패턴  (0) 2022.09.22
인터프리터(Interpreter) 패턴  (0) 2022.09.22
책임 연쇄 패턴  (0) 2022.09.22
프록시(Proxy) 패턴  (0) 2022.09.22
플라이웨이트 (Flyweight) 패턴  (0) 2022.08.16