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 the Strategy pattern is the best choice. With Spring Boot’s powerful dependency injection, Factory pattern comes to the rescue when different subtypes of objects are needed.
Let’s consider an example: you’re building a Report Microservice using Spring Boot. For this example, assume a REST controller with a GET endpoint that will provide data for different types of Report requests. Instead of using lots of ‘if and else’ for different chart requests, I’m going to demonstrate how a combination of Factory and Strategy patterns is a great fit.
The screenshot below shows the ReportController code. The Controller has one endpoint for ‘Engine’ category and another endpoint for ‘ESS’ category.
Report Service is a component that services various categories of reports. As you can see, I have one factory class for each Category. The call from the Service invokes the factory method to get the appropriate report data with reportId, and userId has the inputs.
Factory pattern and Strategy pattern package structure
Factory Pattern is a creational pattern and is one of the most widely used patterns in many frameworks.
Report Id can be a String or an Integer. However, including an Enum for Report Id will be best for Type safety. The screenshot below displays Enum for Engine Report, one each for one report Id.
The screenshot below shows a Factory class that includes a Map containing service classes: one each for one report Id. Report Id Enum is used as the Key for the map to associate a report Id with a Service class for a Report Id.
Traditional Java applications use new operators to create Service instances. However, since this is a Spring Boot application, Spring framework scans the Service classes of a certain type and populates the Map during startup.
This initial post (in a two-part blog series) explained Factory pattern usage in a Spring Boot application. Part 2 of the series will further explore how Strategy pattern is applied alongside Factory Pattern. Stay tuned! In the meantime, if you have any questions about Factory and Strategy patterns that need immediate attention, please don’t hesitate to reach out to us for answers.