A simple explanation and usage of strategy pattern.

  • The main Idea is to define a family of algorithms, encapsulate each one, and make them interchangeable.

Example we want to send emails and the logic will be different depending on the sender.

Without a strategy pattern we usually implement it using switch case, if else conditions.

The drawdowns of this is that everytime that we need to modify the Email sender then we will refactor the whole condition.

  • I think the best principles we should implement are Single Responsibility Principle - Each strategy class has a single responsibility, representing a specific algorithm or behavior. This makes them easy to understand, implement, and test.

  • Open/Closed Principle: The system should be open for extension but closed for modification. New strategies can be added without changing the context or the way client code uses the system.

A simple implementation of strategy pattern.

Create an interface with the action sendEmail because all of the roles will be sending emails right?

Now inherit it on your class that you want to use it. As you can see you can seperate these two if that would make your project more structured on my case this is just an example. Now it’s up to you for the implementation on this one. You can insert this on a service and just call the Roles and then the sendEmail method.

eg. Role1Strategy.SendEmail(email)

The beauty of this implementation is in terms of the code being manageable.

0
Subscribe to my newsletter

Read articles from Juan Miguel Nieto directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Juan Miguel Nieto
Juan Miguel Nieto

A software developer trying to write organic blogs.