Table of contents
No headings in the article.
Design patterns are the principle for oops. By using the right design pattern we can write code that is manageable, reusable, scalable, etc. There are a lot of design patterns to use in LLD. It depends on the use case in which one can be used.
Here In this blog, I am going to explain strategy design patterns. It is one of the behavioural design patterns.
For example, there is a base class vehicle that has two property name, engine. It has a method drive which has normal drive functionality. Now It is inherited by three classes passenger, sport and off-road vehicle. All three need a drive method.
- Passenger vehicle needs normal drive
- Sport vehicle needs special drive
- Off-road vehicle also needs special drive
If we will go with this then class diagram look like below
Here is one thing you folks notice? There is common drive functionality in between sport and off-road vehicle. There will be a common code for both. In the future, if we will have more common things then there will be a lot of duplicate code.
To avoid this, we can use strategy pattern. For that, we can create an interface for that common functionality and define different classes with that interface. Check below class diagram
Now every vehicle can choose its driving style and no code duplicity. The vehicle class can pass its driving style and the same driving style will be used in the vehicle drive method.
Here is the code for it.
DriveStrategy.java interface
public interface DriveStrategy {
public void drive();
}
NormalDrive.java
public class NormalDrive implements DriveStrategy{
@Override
public void drive() {
System.out.println("Drive Normal Mode");
}
}
SpecialDrive.java
public class SpecialDrive implements DriveStrategy{
@Override
public void drive() {
System.out.println("Drive Special Mode");
}
}
Vehicle.java
public class Vehicle {
private String name;
private String engineNumber;
private DriveStrategy driveStrategy;
public Vehicle(DriveStrategy driveStrategy){
this.driveStrategy = driveStrategy;
}
public void drive(){
this.driveStrategy.drive();
}
}
SportVehicle.java
public class SportVehicle extends Vehicle {
public SportVehicle() {
super(new SpecialDrive());
}
}
PassengerVehicle.java
public class PassengerVehicle extends Vehicle {
public PassengerVehicle() {
super(new NormalDrive());
}
}
OffRoadVehicle.java
public class OffRoadVehicle extends Vehicle {
public OffRoadVehicle() {
super(new SpecialDrive());
}
}
Main.java
public class Main {
public static void main(String[] args) {
SportVehicle sportVehicle = new SportVehicle();
sportVehicle.drive();
}
}
I hope, this will help to understand the strategy design pattern. Happy reading, thanks :)