>  기사  >  Java  >  봄의 전략 디자인 패턴

봄의 전략 디자인 패턴

Patricia Arquette
Patricia Arquette원래의
2024-10-21 20:09:03199검색

Strategy Design Pattern in Spring

엔터프라이즈 애플리케이션에서는 비즈니스 요구 사항에 따라 다르게 구현됩니다. 런타임 시 특정 조건에 따라 이들 중 하나를 실행해야 합니다. 일반적인 예로는 정렬 알고리즘, 데이터 암호화, 알림 서비스, 인증 서비스, 결제 서비스 등이 있습니다.

if-else 조건을 사용하는 대신 전략 설계 패턴을 사용하여 구현할 수 있습니다. 전략 디자인 패턴은 런타임에 다양한 구현을 실행/사용하는 데 도움이 됩니다. 전략은 코드 재사용성, 유연성, 관심사 분리확장성

을 제공합니다.

다양한 채널/클라이언트로부터 요청을 받는 통합 인증 서비스를 개발했다고 가정해 보세요. 런타임 시 구성에 따라 인증 목적으로 사용되는 구현을 결정해야 합니다(이는 전달 요청일 수도 있음). 구현은 okta, Azure Ad 또는 자체 IAM일 수 있습니다.

참고: 공급자를 독립 모듈로 구현하고 이를 메인 프로젝트에 종속성으로 추가해야 합니다.

전략 인터페이스

public interface Authentication {

    AuthenticationRes authentication(AuthenticationReq authenticationReq);
    OtpDevicesRes otpDevices(OtpDevicesReq otpDevicesReq);
    SendOtpRes sendOtp(SendOtpReq sendOtpReq);
    VerifyOtpRes verifyOtp(VerifyOtpReq verifyOtpReq);

}

구체적인 전략

@Component("oktaAuthentication")
@Slf4j
public class OktaAuthentication implements Authentication {
    --------------
    --------------
    --------------
}

@Component("ferAuthentication")
@Slf4j
public class FerAuthentication implements Authentication {
      --------------
      --------------
      --------------
}

@Component("eapAuthentication")
@Slf4j
public class EapAuthentication implements Authentication {
      --------------
      --------------
      --------------
}

서비스

@Service
@Slf4j
public class AuthenticationService {

    public Map<String, Authentication> authenticationProvidersMap;
    public Set<String> availableAuthProviders;

    public AuthenticationService(Map<String, Authentication> authenticationProvidersMap) {
        this.authenticationProvidersMap = authenticationProvidersMap;
        this.availableAuthProviders = this.authenticationProvidersMap.keySet();
        log.info("Available Auth providers:{}", this.availableAuthProviders);
    }

    public AuthenticationRes getAuthentication(AuthenticationReq authenticationReq, ClientDetails clientDetails) {

        //This method will identify authentication provider based on client details
        // and returns oktaAuthentication/eapAuthentication/ferAuthentication
        String authProvider = getAuthProviderDetails(clientDetails);

        if (this.availableAuthProviders.contains(authProvider)) {
            return this.authenticationProvidersMap.get(authProvider)
                    .authentication(authenticationReq);
        } else {
            throw new AuthProviderUnavailable(authProvider);
        }

    }


    public String getAuthProviderDetails(ClientDetails clientDetails) {
        // implement your business logic to return the provider that need to be used. 
    }
}

질문이 있으시면 댓글로 질문을 남겨주세요.

위 내용은 봄의 전략 디자인 패턴의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.