전략패턴

Trace·2024년 8월 28일

Design-Pattern

목록 보기
7/7

전략패턴이란

전략 (정체) 패턴이란 전략이라고 부르는 ‘캡슐화한 알고리즘’ 을 컨텍스트 (어떤 행위, 어떤 상태, 어떤 상황) 안에서 바꿔주면서 상호 교체가 가능하게 만드는 디자인 패턴

context(ex)로그인) 이라는 행위를 하는데 Local Stragy, 간편 로그인 (카카오, 네이버, 구글 등..) 등 전략 (정체)를 간편하게 교체 할 수 있는 방법을 전략 패턴이라고 함

전략패턴의 구조

  1. Context: 클라이언트가 사용하는 인터페이스를 정의, 이 클래스는 전략을 구성하는 인터페이스를 가지고 있으며, 알고리즘을 실행하기 위해 전략 객체를 사용
  2. Strategy Interface: 알고리즘을 정의하는 공통 인터페이스, 다양한 전략들이 이 인터페이스를 구현
  3. Concrete Strategy: 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님이 카카오로 로그인했습니다."
profile
개발하는사람

0개의 댓글