전략 (정체) 패턴이란 전략이라고 부르는 ‘캡슐화한 알고리즘’ 을 컨텍스트 (어떤 행위, 어떤 상태, 어떤 상황) 안에서 바꿔주면서 상호 교체가 가능하게 만드는 디자인 패턴
context(ex)로그인) 이라는 행위를 하는데 Local Stragy, 간편 로그인 (카카오, 네이버, 구글 등..) 등 전략 (정체)를 간편하게 교체 할 수 있는 방법을 전략 패턴이라고 함
Strategy Interface를 구현한 클래스, 각각의 클래스는 하나의 알고리즘을 구현// Strategy Interface
class SocialLoginStrategy {
login(userId, userPassword) {
throw new Error("This method should be overridden!");
}
}
// Concrete Strategies
class NaverLoginStrategy extends SocialLoginStrategy {
login(userId, userPassword) {
console.log(`Logging in with Naver ID: ${userId}`);
// 네이버 로그인 로직을 여기에 구현
// 예를 들어, 네이버 API를 호출하는 코드를 여기에 작성합니다.
return `${userId}님이 네이버로 로그인했습니다.`;
}
}
class KakaoLoginStrategy extends SocialLoginStrategy {
login(userId, userPassword) {
console.log(`Logging in with Kakao ID: ${userId}`);
// 카카오 로그인 로직을 여기에 구현
// 예를 들어, 카카오 API를 호출하는 코드를 여기에 작성합니다.
return `${userId}님이 카카오로 로그인했습니다.`;
}
}
// Context
class AuthContext {
constructor(strategy) {
this.strategy = strategy;
}
setStrategy(strategy) {
this.strategy = strategy;
}
authenticate(userId, userPassword) {
return this.strategy.login(userId, userPassword);
}
}
// Client code
const authContext = new AuthContext(new NaverLoginStrategy());
console.log(authContext.authenticate("user123", "password")); // "user123님이 네이버로 로그인했습니다."
authContext.setStrategy(new KakaoLoginStrategy());
console.log(authContext.authenticate("user456", "password")); // "user456님이 카카오로 로그인했습니다."