[디자인 패턴] 전략 패턴

k·2024년 2월 12일
0

디자인 패턴

목록 보기
3/4

전략 패턴

전략 패턴이 뭐야?

해당 패턴은 전략 패턴 외에도 정책 패턴이라는 말을 가지고 있다.

이 패턴은 객체의 행위를 바꾸고 싶은 경우에 직접 수정하지않고 전략이라고 부르는 캡슐화한 알고리즘을 컨텍스트안에서 바꿔주면서 상호교체가 가능하게 만드는 패턴이다.

컨텍스트

컨텍스트라는 말을 너무 많이 듣는데, 마음으로는 알지만 머리로는 이해하지 못해서 따로 정리한다.

컨텍스트는 상황, 맥락, 문맥을 의미하며 개발자가 어떠한 작업을 완료하는데 필요한 모든 관련 정보를 말한다.

그게 보통 어디서 쓰이는데?

Express 기반으로 웹을 만들어본 사람들은 이 패턴을 보기만 했어도 어디서 본 적이 있는 형태라고 생각했을 것이다.

passport가 그 대표적인 예시다.

각 인증에 맞게 전략을 넣어서 사용하게 된다.

const passport = require("passport")
const LocalStrategy = require('passport-local').Strategy

passport.use(new LocalStrategy(...))

위와 같은 형태로 전략을 주입해서 로직을 수행 하는 것을 볼 수 있다.

기본적인 틀을 만들어보자!

interface AuthenticationStrategy{
    public void authentication();
}
class NaverAuthenticationStrategy implements AuthenticationStrategy{
    @Override
    public void authentication() {
        System.out.println("Naver auth");
    }
}

class KakaoAuthenticationStrategy implements  AuthenticationStrategy{
    @Override
    public void authentication() {
        System.out.println("Kakao auth");
    }
}
class AuthenticationService{
    public void authentication(AuthenticationStrategy authenticationStrategy){
        authenticationStrategy.authentication();
    }
}

public class Main {
    public static void main(String[] args) {
        AuthenticationService authenticationService = new AuthenticationService();
        authenticationService.authentication(new KakaoAuthenticationStrategy());
        authenticationService.authentication(new NaverAuthenticationStrategy());
    }
}

인터페이스를 통해 추상 레이어를 구성하고 이를 이용해 필요에 따라서 구현체를 만들게 된다.

사용자가 서비스 로직을 수행할 때, 주입을 받아서 여러 전략에 대응할 수 있게한다.

profile
You must do the things you think you cannot do

0개의 댓글