architecture/Design Pattern
[디자인 패턴] 커맨드 패턴 (Command Pattern)
Hero_O
2022. 9. 28. 21:36
디자인 패턴 - 커맨드 패턴
💡 요청을 캡슐화 해서 요청자(Invoker)와 수신자(receiver)를 분리하는 패턴으로 요청의 구현 내용이 바뀌더라도 요청자가 변경되지 않고 커맨드가 확장 될 수 있어 객체지향 원칙 OCP(Open Closed Principle)를 지킬 수 있다.
🎯 하나의 인터페이스를 통해 여러개의 구체적인 요청(Command)을 호출하도록 한다.
객체 모델
구현
👉 Command
@FunctionalInterface
public interface Command {
void execute();
}
Command
는 로직을 추상화 한다.
👉 ConcreteCommand
public class FirstConcreteCommand implements Command{
private Receiver receiver;
public FirstConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
System.out.println("첫번째 구체 명령 - receiver : " + receiver.getName());
}
}
👉 Invoker(요청자)
public class Invoker {
private Command command;
public Invoker(Command command) {
this.command = command;
}
public void invoke() {
command.execute();
}
}
👉 Receiver(수신자)
public class Receiver {
private String name;
public Receiver() {
}
public Receiver(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
👉 main()
public static void main(String[] args) {
Receiver hero = new Receiver("Hero");
Receiver chad = new Receiver("Chad");
Invoker heroInvoker = new Invoker(new FirstConcreteCommand(hero));
// 👉 CreteCommand를 람다를 통해 구현
Invoker chadInvoker = new Invoker(()
-> System.out.println("두번째 구체 명령 - receiver : " + chad.getName()));
heroInvoker.invoke();
chadInvoker.invoke();
}
𝌞 결과
👍 장점
- 기존 코드 수정없이 새로운 커맨드를 생성할 수 있다. 즉, OCP(Open Closed Principle) 를 지킬 수 있다.
- 수신자의 코드 변경에 클라이언트가 영향을 받지 않을 수 있다. 즉, 느슨한 결합(Loose coupling)을 이룬다.
🎯 예제코드
GitHub - icraft2170/Blog-Example-Code
Contribute to icraft2170/Blog-Example-Code development by creating an account on GitHub.
github.com
참조
코딩으로 학습하는 GoF의 디자인 패턴 - 인프런 | 강의
디자인 패턴을 알고 있다면 스프링 뿐 아니라 여러 다양한 기술 및 프로그래밍 언어도 보다 쉽게 학습할 수 있습니다. 또한, 보다 유연하고 재사용성이 뛰어난 객체 지향 소프트웨어를 개발할
www.inflearn.com
GoF의 디자인 패턴 :재사용성을 지닌 객체지향 소프트웨어의 핵심요소 - 교보문고
▶ 이 책은 디자인 패턴을 다룬 이론서입니다. 디자인 패턴의 기초적이고 전반적인 내용을 학습할 수 있습니다.
www.kyobobook.co.kr