Overview

요청을 객체 형태로 캡슐화하여(실행할 함수를 캡슐화하여) 사용자가 요청한 메서드 이름, 매개변수 등의 정보를 나중에 저장, 로깅 또는 사용할 수 있도록 하는 패턴입니다. 요청에 필요한 정보를 취소합니다.
명령 패턴은 항상 명령, 수신자, 호출자 및 클라이언트의 네 가지 용어를 따릅니다.

장점
명령 패턴을 활용하여 요청 부분과 작업 부분을 분리함으로써 시스템의 결합 정도를 낮출 수 있으며, 각 객체가 수정되어도 다른 객체에는 영향을 미치지 않습니다.
클라이언트와 Invoker클래스 간의 종속성이 제거됩니다.

단점
수신자의 액션을 추가하면 액션에 대한 클래스를 생성해야 하므로 잡다한 클래스가 오히려 많이 추가되는 단점이 있습니다.

 

Structure

https://ko.wikipedia.org/wiki/%EC%BB%A4%EB%A7%A8%EB%93%9C_%ED%8C%A8%ED%84%B4

 

Code Example

package com.example.design.pattern;

interface Command {
	public abstract void execute();
}

class Button {
	private Command theCommand;

	public Button(Command theCommand) {
		setCommand(theCommand);
	}

	public void setCommand(Command newCommand) {
		this.theCommand = newCommand;
	}

	public void pressed() {
		theCommand.execute();
	}
}

class Lamp {
	public void turnOn() {
		System.out.println("Lamp On");
	}
}

class LampOnCommand implements Command {
	private Lamp theLamp;

	public LampOnCommand(Lamp theLamp) {
		this.theLamp = theLamp;
	}

	public void execute() {
		theLamp.turnOn();
	}
}

class Alarm {
	public void start() {
		System.out.println("Alarming");
	}
}

class AlarmStartCommand implements Command {
	private Alarm theAlarm;

	public AlarmStartCommand(Alarm theAlarm) {
		this.theAlarm = theAlarm;
	}

	public void execute() {
		theAlarm.start();
	}
}

public class MyCommand {
	public static void main(String[] args) {
		Lamp lamp = new Lamp();
		Command lampOnCommand = new LampOnCommand(lamp);
		Alarm alarm = new Alarm();
		Command alarmStartCommand = new AlarmStartCommand(alarm);

		Button button1 = new Button(lampOnCommand); 
		button1.pressed();

		Button button2 = new Button(alarmStartCommand);
		button2.pressed(); 
		button2.setCommand(lampOnCommand);
		button2.pressed(); 
	}
}

 

Console Result

Lamp On
Alarming
Lamp On

 

Conclusion

N/A

728x90

+ Recent posts