Command
Command ํจํด์ ์คํ๋ ๊ธฐ๋ฅ(๋ช ๋ น)์ ํ๋์ ๊ฐ์ฒด๋ก ์บก์ํํ์ฌ, ํธ์ถ์์ ์ํ์ ์ฌ์ด์ ๊ฒฐํฉ๋๋ฅผ ๋ฎ์ถ๊ณ , ๋ช ๋ น์ ์ฌ์ฌ์ฉ์ฑ, ํ์, ์ทจ์ ๊ธฐ๋ฅ ๋ฑ ๋ค์ํ ํ์ฅ์ ๊ฐ๋ฅํ๊ฒ ํ๋ ๋์์ธ ํจํด์ ๋๋ค.
+---------------------+
| Command | <-- ์คํํ ๊ธฐ๋ฅ์ ์บก์ํํ ์ธํฐํ์ด์ค
+---------------------+
| + execute() |
+---------------------+
โฒ
โโโโโโโโโโโดโโโโโโโโโโ
โ โ
+----------------------+ +----------------------+
| ConcreteCommand1 | | ConcreteCommand2 | <-- ๊ตฌ์ฒด์ ์ธ ๋ช
๋ น ๊ตฌํ
+----------------------+ +----------------------+
| - receiver: Receiver | | - receiver: Receiver |
| + execute() | | + execute() |
+----------------------+ +----------------------+
โ
โผ
+--------------+
| Receiver | <-- ๋ช
๋ น์ ์ค์ ์ํํ๋ ๊ฐ์ฒด
+--------------+
| + action() |
+--------------+
โฒ
โ
+--------------+
| Invoker | <-- ๋ช
๋ น ์คํ์ ์์ฒญํ๋ ๊ฐ์ฒด
+--------------+
| - command: Command |
| + setCommand(c: Command) |
| + invoke() |
+--------------+
์ฆ, ์คํํ ์์ ์ Command ์ธํฐํ์ด์ค์ ์ ์ํ๊ณ , ์ด๋ฅผ ๊ตฌํํ ๊ตฌ์ฒด์ ์ธ Command ๊ฐ์ฒด๋ฅผ ์์ฑํ์ฌ, ํด๋ผ์ด์ธํธ๋ ์ด Command ๊ฐ์ฒด๋ฅผ ํธ์ถํ๋ ๋ฐฉ์์ผ๋ก ์์ ์ ์ํํ ์ ์์ต๋๋ค.
How do Codeโ
// Command ์ธํฐํ์ด์ค: ์คํํ ๋ช
๋ น์ ์ ์
public interface Command {
void execute();
}
// Receiver: ๋ช
๋ น์ ์ค์ ์ํํ๋ ๊ฐ์ฒด
public class Receiver {
public void action() {
System.out.println("Receiver์ action() ๋ฉ์๋ ์คํ");
}
}
// ConcreteCommand: Command ์ธํฐํ์ด์ค ๊ตฌํ, Receiver๋ฅผ ํตํด ์์
์ ์ํ
public class ConcreteCommand implements Command {
private Receiver receiver;
public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
System.out.println("ConcreteCommand: execute() ํธ์ถ");
receiver.action();
}
}
// Invoker: ๋ช
๋ น ์คํ์ ์์ฒญํ๋ ๊ฐ์ฒด
public class Invoker {
private Command command;
// ๋ช
๋ น ๊ฐ์ฒด๋ฅผ ์ค์
public void setCommand(Command command) {
this.command = command;
}
// ์ค์ ๋ ๋ช
๋ น์ ์คํ
public void invoke() {
if (command != null) {
command.execute();
}
}
}
Command ์ธํฐํ์ด์ค
execute()
๋ฉ์๋๋ฅผ ์ ์ํ์ฌ, ํธ์ถ ์ ์คํ๋ ๊ธฐ๋ฅ์ ์บก์ํํฉ๋๋ค.
ConcreteCommand ํด๋์ค:
Command ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ๋ฉฐ, ๋ด๋ถ์ Receiver ๊ฐ์ฒด๋ฅผ ๊ฐ์ง๊ณ ์์ต๋๋ค.
execute()
ํธ์ถ ์ Receiver์ ํน์ ๋ฉ์๋๋ฅผ ํธ์ถํ์ฌ ์ค์ ์์ ์ ์ํํฉ๋๋ค.
Receiver
์ค์ ๋ช ๋ น์ ์ํํ๋ ๊ฐ์ฒด๋ก, Command ๊ฐ์ฒด์ ์ํด ํธ์ถ๋ฉ๋๋ค.
Invoker
ํด๋ผ์ด์ธํธ๊ฐ ๋ช ๋ น ์คํ์ ์์ฒญํ๋ ๊ฐ์ฒด์ ๋๋ค.
Command ๊ฐ์ฒด๋ฅผ ์ค์ (setCommand)ํ๊ณ , ํ์ํ ๋
invoke()
๋ฉ์๋๋ฅผ ํธ์ถํ์ฌ ๋ช ๋ น์ ์คํํฉ๋๋ค.
์ฅ์
๋ช ๋ น ์บก์ํ๋ฅผ ํตํด ํธ์ถ์์ ์ํ์ ๊ฐ์ ๊ฒฐํฉ๋๋ฅผ ๋ฎ์ถ๋ฉฐ, ๋ช ๋ น์ ๊ฐ์ฒด๋ก ๊ด๋ฆฌํ ์ ์์ต๋๋ค.
๋ช ๋ น ํ, ์ทจ์(undo), ๋ก๊น ๋ฑ ๋ค์ํ ๊ธฐ๋ฅ ํ์ฅ์ด ์ฉ์ดํด์ง๋๋ค.
Last updated