ホームページ  >  記事  >  Java  >  春の戦略設計パターン

春の戦略設計パターン

Patricia Arquette
Patricia Arquetteオリジナル
2024-10-21 20:09:03199ブラウズ

Strategy Design Pattern in Spring

エンタープライズ アプリケーションでは、ビジネス要件に応じてさまざまな実装が行われます。実行時には、特定の条件に基づいてこれらのうち 1 つを実行する必要があります。一般的な例としては、並べ替えアルゴリズム、データ暗号化、通知サービス、認証サービス、支払いサービスなどがあります...

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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。