首页  >  文章  >  Java  >  Spring策略设计模式

Spring策略设计模式

Patricia Arquette
Patricia Arquette原创
2024-10-21 20:09:03201浏览

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