1. 컀맨λ ν¨ν΄(command pattern)
컀맨λ ν¨ν΄μ νΈμΆμ(ν΄λΌμ΄μΈνΈ λλ νΈμΆμ) μ μμ μ(μμ μν κ°μ²΄)μμ λΆλ¦¬(decoupling) νμ¬ μ μ°μ±κ³Ό νμ₯μ±μ μ 곡νλ ν¨ν΄μ΄λ€. μ¦, νΈμΆμμ μ½λλ₯Ό λ³κ²½νμ§ μκ³ λ€μν λ§€κ°λ³μλ₯Ό μ¬μ©ν΄ λ€μν λͺ λ Ήμ μμ±ν μ μλ€. μμ²μ μΊ‘μνν΄μ ν΄λΉ μμ² μμμ μνν λμμ μ€μ νκ³ μμ μλ₯Ό νΈμΆν λ νΈμΆν νλκ³Ό νμν νλΌλ―Έν°μ κ΄ν λͺ¨λ μ 보λ€μ 컀맨λ(command) λΌλ μΈν°νμ΄μ€ μμΌλ‘ μΊ‘μννκΈ° λλ¬Έμ κΈ°λ₯μ μ¬μ¬μ©ν μ μλ€.
컀맨λ ν¨ν΄μ OCP μ μ€νν μ μλ μ₯μ μ΄ μλ€. νΈμΆμ μͺ½μ μ½λκ° λ³κ²½λμ§ μμΌλ©° κΈ°λ₯(command) μΊ‘μν λ° μΆκ°ν μ μκΈ° λλ¬Έμ΄λ€. νμ§λ§, κΈ°λ₯(command) κ° μ¦κ°ν μλ‘ λ³΅μ‘λκ° μ¦κ°ν μ μλ λ¨μ μ΄ μ‘΄μ¬νλ€.
sample code (μΆμ² : inflearn - μ½λ©μΌλ‘ νμ΅νλ GoFμ λμμΈ ν¨ν΄)
public static void main(String[] args) {
Button button = new Button();
button.press(new LightOnCommand(new Light()));
button.undo();
}
public class Button {
private Stack<Command> commands = new Stack<>();
public void press(Command command) {
command.execute();
commands.push(command);
}
public void undo() {
if (!commands.isEmpty()) {
Command command = commands.pop();
command.undo();
}
}
}
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
@Override
public void undo() {
new LightOffCommand(this.light).execute();
}
}
2. μ¬μ© μμ
java μμλ ExecutorService interface μμ 컀맨λ ν¨ν΄μΌλ‘ κΈ°λ°μ μ€κ³λμ΄ κ΅¬νλμλ€. νλΌλ―Έν°λ₯Ό Runnable interface νμ ꡬν체λ₯Ό μμ±νμ¬ νλμ μ μν΄ κΈ°λ₯μ λμνλ€.
public static void main(String[] args) {
Light light = new Light();
Game game = new Game();
ExecutorService executorService = Executors.newFixedThreadPool(4);
executorService.submit(light::on);
executorService.submit(game::start);
executorService.submit(game::end);
executorService.submit(light::off);
executorService.shutdown();
}

Spring μ§μμμ 컀맨λ ν¨ν΄μ κΈ°λ°μΌλ‘ ꡬνλ μμλ‘λ SimpleJdbcInsert, SimpleJdbcCall μ΄λ€. insert 쿼리μ stored procedure λ₯Ό νΈμΆν λ νμν λͺ¨λ μ 보λ₯Ό κ°μ§κ³ νλμ 컀맨λ μ€λΈμ νΈλ₯Ό ν΅ν΄ κ΄λ¦¬νκ³ λ‘μ§μ΄ λμνλ ν΄λμ€λ₯Ό λ³λλ‘ μ μν΄μ μννκ³ μλ€.
SimpleJdbcInsert insert = new SimpleJdbcInsert(dataSource)
.withTableName("command")
.usingGeneratedKeyColumns("id");
Map<String, Object> data = new HashMap<>();
data.put("name", command.getClass().getSimpleName());
data.put("when", LocalDateTime.now());
insert.execute(data);
λ€μ΄μ΄κ·Έλ¨μ νμΈν΄λ³΄λ©΄ μμμ SimpleJdbcInsertOperations interface κ° μ‘΄μ¬νλ©°, excute() λ©μλμ κ΄ν΄ μ μλμ΄ μλ€.

Reference
- [geeksforgeeks] command-pattern : https://www.geeksforgeeks.org/command-pattern/?ref=lbp
- [inflearn] μ½λ©μΌλ‘ νμ΅νλ GoFμ λμμΈ ν¨ν΄
'π programming-language > java' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
| μ΄λν° ν¨ν΄(adapter pattern) (1) | 2024.07.09 |
|---|---|
| νΌμ¬λ ν¨ν΄(Facade Pattern) (0) | 2024.07.08 |
| μ± μ μ°μ ν¨ν΄ (chain of responsibility pattern) (1) | 2024.07.05 |
| μ±κΈν€ ν¨ν΄(singleton pattern) (0) | 2024.07.03 |
| μ λ° μ°μ°μλ BigDecimal μ μ¬μ©νμ (0) | 2024.04.24 |