首頁  >  文章  >  Java  >  Spring策略設計模式

Spring策略設計模式

Patricia Arquette
Patricia Arquette原創
2024-10-21 20:09:03196瀏覽

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. 
    }
}

如果有任何問題請在留言區留言。

以上是Spring策略設計模式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn