In enterprise applications, we will have different implementations to our business requirements. At run time we need to execute one out of those based on certain conditions. Common examples are sorting algorithms, data encryption, notification services, authentication services, payment services...
Instead of using if-else conditions, we can use a strategy design pattern to implement it. Strategy design pattern will help us to run/use different implementations at run time. Strategy provides code reusability, flexibility, separation of concerns and extensibility.
Consider you have developed a unified authentication service which will receive requests from different channels/clients. At run time, based on configuration, you need to decide the implementation used for authentication purposes (This could be request forward too). Your implementations can be okta, Azure Ad, or Your Own IAM.
Note: We need to implement providers as independent modules and add it to the main project as dependency.
Strategy Interface
public interface Authentication { AuthenticationRes authentication(AuthenticationReq authenticationReq); OtpDevicesRes otpDevices(OtpDevicesReq otpDevicesReq); SendOtpRes sendOtp(SendOtpReq sendOtpReq); VerifyOtpRes verifyOtp(VerifyOtpReq verifyOtpReq); }
Concrete Strategies
@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
@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. } } </string></string></string>
If you have any question please leave a question in comments section.
The above is the detailed content of Strategy Design Pattern in Spring. For more information, please follow other related articles on the PHP Chinese website!

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 English version
Recommended: Win version, supports code prompts!
