행동 패턴(Behavioral Patterns) 톺아 보기! 🎭
“객체들이 서로 대화하고 협력하려면 어떤 규칙이 필요할까?”
이번엔 행동 패턴(Behavioral Patterns)의 세계로 떠나볼게요.
행동 패턴은 객체 간의 소통 방식과 책임을 분배하는 데 초점이 맞춰져 있어요. 프론트엔드에서 데이터 흐름, 이벤트 처리, 상태 관리와 관련된 많은 문제가 이 패턴들로 해결됩니다.
행동 패턴은 코드에서 “어떻게 하면 더 똑똑하게 협력할 수 있을까?”라는 질문에 답을 줍니다. 함께 살펴볼까요?
🧩 행동 패턴이란?
행동 패턴은 객체들이 어떻게 상호작용하고 책임을 나눌지 설계합니다.
이 패턴들은 다음과 같은 목표를 가지고 있죠:
- 객체 간 커뮤니케이션 단순화: 복잡한 상호작용을 추상화하여 깔끔한 구조 제공
- 책임 분리: 각 객체가 “어떤 역할”을 맡을지 명확히 구분
- 유연성 증가: 객체 간 결합도를 낮추어 코드 수정 및 확장이 용이.
🎭 주요 행동 패턴들
1️⃣ 옵저버 패턴(Observer Pattern)
변화를 감지하고 알림을 전파하라!
옵저버 패턴은 한 객체의 상태 변화가 다른 객체들에게 자동으로 알림을 보내는 구조입니다.
React의 상태 관리나 이벤트 시스템에서 자주 볼 수 있는 개념이죠.
🚀 코드 예제: 옵저버 패턴
class Subject {
constructor() {
this.observers = [];
}
addObserver(observer) {
this.observers.push(observer);
}
notifyObservers(message) {
this.observers.forEach((observer) => observer.update(message));
}
}
class Observer {
update(message) {
console.log(`Observer received message: ${message}`);
}
}
// 사용 예시
const subject = new Subject();
const observer1 = new Observer();
const observer2 = new Observer();
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.notifyObservers("Hello, World!");
// Observer received message: Hello, World!
// Observer received message: Hello, World!
📝 설명:
- Subject(주제): 상태 변화를 감지하고 옵저버들에게 알림을 전달
- Observer(관찰자): 알림을 받고 작업을 수행
🤔 언제 쓰나요?
- 상태가 변화할 때 자동으로 UI를 업데이트해야 할 때
- 이벤트 시스템이나 전역 상태 관리가 필요한 경우
2️⃣ 전략 패턴(Strategy Pattern)
다양한 전략 중 하나를 선택해서 써보자!
전략 패턴은 여러 알고리즘 중 하나를 선택해서 실행할 수 있는 구조를 제공합니다.
React에서 다른 로직을 처리하는 핸들러 함수를 동적으로 바꿔야 할 때 유용합니다.
🚀 코드 예제: 전략 패턴
class PaymentStrategy {
pay(amount) {
throw new Error("This method should be overridden!");
}
}
class CreditCardPayment extends PaymentStrategy {
pay(amount) {
console.log(`Paid ${amount} using Credit Card`);
}
}
class PayPalPayment extends PaymentStrategy {
pay(amount) {
console.log(`Paid ${amount} using PayPal`);
}
}
class PaymentContext {
constructor(strategy) {
this.strategy = strategy;
}
setStrategy(strategy) {
this.strategy = strategy;
}
executePayment(amount) {
this.strategy.pay(amount);
}
}
// 사용 예시
const payment = new PaymentContext(new CreditCardPayment());
payment.executePayment(100); // Paid 100 using Credit Card
payment.setStrategy(new PayPalPayment());
payment.executePayment(200); // Paid 200 using PayPal
📝 설명:
- 전략은 변경 가능하며, 실행 시점에 동적으로 선택할 수 있습니다.
- 코드를 조건문 없이 유연하게 확장할 수 있는 구조를 제공합니다.
🤔 언제 쓰나요?
- 다양한 알고리즘 중 하나를 선택해야 할 때
- 비즈니스 로직을 유연하게 설계하고 싶을 때
3️⃣ 커맨드 패턴(Command Pattern)
작업을 명령 객체로 만들어 처리하자!
커맨드 패턴은 작업을 독립적인 객체로 캡슐화하여 실행, 취소, 재실행이 가능하도록 합니다.
React에서 상태 관리와 액션 처리를 단순화할 때 도움이 됩니다.
🚀 코드 예제: 커맨드 패턴
class Command {
execute() {
throw new Error("This method should be overridden!");
}
}
class LightOnCommand extends Command {
execute() {
console.log("Light is ON");
}
}
class LightOffCommand extends Command {
execute() {
console.log("Light is OFF");
}
}
class RemoteControl {
setCommand(command) {
this.command = command;
}
pressButton() {
this.command.execute();
}
}
// 사용 예시
const remote = new RemoteControl();
const lightOn = new LightOnCommand();
const lightOff = new LightOffCommand();
remote.setCommand(lightOn);
remote.pressButton(); // Light is ON
remote.setCommand(lightOff);
remote.pressButton(); // Light is OFF
📝 설명:
- 명령 객체는 작업을 표현하며, 실행 시점을 제어할 수 있습니다.
- 작업 실행 외에 취소, 기록, 반복 등의 동작도 지원 가능합니다.
🤔 언제 쓰나요?
- 작업을 캡슐화하고 실행을 관리해야 할 때
- UI에서 명령 실행(예: 버튼 클릭)을 쉽게 처리하고 싶을 때
4️⃣ 미디에이터 패턴(Mediator Pattern)
모든 객체가 미디에이터를 통해 대화하도록 하자!
미디에이터 패턴은 객체들이 서로 직접 통신하지 않고, 중재자를 통해 협력하도록 합니다.
이로 인해 객체 간 의존성이 줄어들고, 코드가 더 간결해지죠.
🚀 코드 예제: 미디에이터 패턴
class Mediator {
constructor() {
this.participants = [];
}
register(participant) {
this.participants.push(participant);
participant.setMediator(this);
}
send(message, sender) {
this.participants
.filter((participant) => participant !== sender)
.forEach((participant) => participant.receive(message));
}
}
class Participant {
setMediator(mediator) {
this.mediator = mediator;
}
send(message) {
this.mediator.send(message, this);
}
receive(message) {
console.log(`Received: ${message}`);
}
}
// 사용 예시
const mediator = new Mediator();
const participant1 = new Participant();
const participant2 = new Participant();
mediator.register(participant1);
mediator.register(participant2);
participant1.send("Hello!"); // Received: Hello!
📝 설명:
- 미디에이터는 객체 간 직접적인 의존성을 제거합니다.
- React에서 컴포넌트 간 상태 공유를 단순화할 때 유용합니다.
🤔 언제 쓰나요?
- 객체 간 복잡한 상호작용을 단순화해야 할 때
- 중앙에서 통합적으로 상태나 이벤트를 관리하고 싶을 때
🎯 프론트엔드에서 행동 패턴 활용하기
- 옵저버 패턴: 전역 상태 관리나 이벤트 처리
- 전략 패턴: 다양한 UI 동작을 조건 없이 처리
- 커맨드 패턴: 작업 실행 및 상태 관리
- 미디에이터 패턴: 컴포넌트 간 이벤트 중재
🌷전설의 개발자가 되어봅시당!🌷
'디자인 패턴' 카테고리의 다른 글
[Design Pattern] 구조 패턴(Structural Patterns) 🏗️✨ (1) | 2025.01.16 |
---|---|
[Design Pattern] 생성 패턴(Creational Patterns) 🏗️ (0) | 2025.01.15 |
[Design Pattern]프론트엔드에 적용되는 디자인 패턴들! 🍭 (0) | 2025.01.14 |
[Design Pattern] Atomic Design🧪 (2) | 2025.01.02 |