Strategy and Factory Pattern in a Spring Boot Application: Part II
Strategy and Factory patterns are the most useful design patterns in any application. If you have a branching code with lots of ‘if and else’, then Strategy pattern is the best choice. With Spring Boot’s powerful dependency injection, Factory pattern comes to the rescue when different sub types of objects are needed. This is a continuation of Part I of the blog series, which detailed the proper use of the Factory Pattern.
The starting point for Strategy Pattern is an interface that has two methods. One method is to get the Report Id Enum and another method is to get the actual report data based on the user id. I created a default method and added code to get some mock data for each report id before the actual implementation is done. When the actual implementation is done, this default method will no longer be used. Also, having a default method ensures backward compatibility without breaking the code.
Service classes: one each for one Report Id in the Enum class
The screenshot below shows two service classes: one each for one Report Id Enum class that implements Report Interface for Engine.
Initially, I have not added the actual implementation in the Service class. This would work fine as we have a default method in the interface that returns the mock data from a JSON file.
Service classes with actual implementation
The screenshot below shows the Service call with an actual implementation, which will circumvent the default method in the interface.
UML Diagrams of Service classes
A combination of Factory and Strategy pattern is a great gift when designing solutions in a clean way without having to have the clumsy ‘if and else’ in the code. Part I of this series explained Factory pattern usage in a Spring Boot application. This post explored how Strategy pattern is applied alongside Factory Pattern. Thanks for reading! If you continue to have any questions around Factory and Strategy patterns, please don’t hesitate to reach out to us for answers.