- read

Why Should We Use the Strategy Pattern in Spring Boot

Kishore Karnatakapu 50

Why Should We Use the Strategy Pattern in Spring Boot

Kishore Karnatakapu
Level Up Coding
Published in
4 min readJust now

--

How to Use the Strategy Pattern to Implement Different Business Rules in Spring Boot

Strategy design pattern is a behavioral design pattern which can be useful when you have multiple ways of performing an action and you want to be able to choose the best one for the current situation.

For example, imagine you have a notification application that allows users to notify for their notifications using different methods, such as SMS, email, Whatsapp. You could use the Strategy pattern to implement each method as a separate strategy class. Then, at runtime, you could inject the appropriate strategy class into your application and use it to process the notifications.

Implementation of Strategy Pattern:

We need a spring boot project from the initializer website.

Project Structure

application.properties and StrategyPatternApplication.java have default main codes and properties. We didn’t add anything.

  • Let’s create an Enum class that name is NotificationType. This class just will have said to us which type of notification they have.
public enum NotificationType {
SITE,
SMS,
EMAIL
}
  • Create an interface that has sendMessage and notificationType methods. Because we have different platforms that we need to send.
public interface NotificationStrategy {
void sendMessage(String message);
NotificationType notificationType();
}
  • Now we can create a few classes in which we implement the NotificationStrategy class.

For Email Notification

@Slf4j
@Component
public class EmailNotificationStrategy implements NotificationStrategy {
@Override
public void sendMessage(String message) {
log.info("message send to email" + message);
}
@Override
public NotificationType notificationType() {
return NotificationType.EMAIL;
}
}

For website Notification

@Slf4j
@Component
public class…