Strategy Pattern
Hello everyone, I hope you are all donig well! Today we will dive in and learn about Strategy pattern which is one of the behavioral design patterns.
As a developer we can add to our Project more than one payment system right? or we can can send messages/Notifications with email or sms to customers. When there is more than one option Strategy pattern can be a way to handle that cases. So we can use Strategy desing pattern when there are more than one option and make the users or company change it on runtime.
The Strategy design pattern is a great choice when you have multiple algorithms or behaviors and want to make them interchangeable. It allows you to define a family of algorithms, encapsulate each one, and make them interchangeable
Lets assume we have a company and we are sending to our customers notifications about new prices. And we are sending notifications as an email. After a while we are saying that every person does not check their Email address so maybe we should send an SMS instead of Email. So now we are still sending notifications but not with Email with SMS. we may back to the Mail notifications again or we can use something else to sends notifications. Even we can let the user to chose how to take notifications (SMS/Email).That’s where we can use Strategy Pattern. When we have more than one solution and if we want to implement all of them or make the project open for new implementations we can use Strategy design pattern. But how? lets talk about that.
The main point is to create an interface about notifications and add the function so every class which implements that class can implement it class as its own way.
we are creating an interface and creating functions for implemting classes. In this example the interface →
public interface INotificationStrategy
{
void SendNotification(string message);
}
INotificationStrategy and we added SendNotification function. Now we will create Implementing classes → SMSNotification and MailNotification.
public class SMSNotification : INotificationStrategy
{
public void SendNotification(string message)
{
Console.WriteLine($"{message}");
Console.WriteLine("This is an SMS Notification");
}
}
public class MailNotification : INotificationStrategy
{
public void SendNotification(string message)
{
Console.WriteLine($"{message}");
Console.WriteLine("This is an Email Notification");
}
}
and in this SMS and Mail class we are implementing INotificationStrategy
so if we want to add a new way to send notifications without change any old code blog we can just add a new class and implement INotificationStrategy so thats how Strategy pattern works.
I am learning a lot while I am writing I hope you learned a lot too while you are reading and enjoyed it. Don’t forget to follow on Medium to keep learning together. See you soon :)
Happy coding!