-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrategyDesignPattern.java
More file actions
140 lines (62 loc) · 2.46 KB
/
StrategyDesignPattern.java
File metadata and controls
140 lines (62 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package LLD;
//Strategy is a behavioral design pattern that lets you define a family of algorithms,
//put each of them into a separate class, and make their objects interchangeable.
class Vehicle {
//constructor injection
DriveStrategy driveStrategy;
Vehicle(DriveStrategy driveStrategy) {
this.driveStrategy = driveStrategy;
}
public void drive() {
//calling drivestrategy of particular vehicle
this.driveStrategy.drive();
}
}
class OffRoadVehicle extends Vehicle {
OffRoadVehicle(){
super( new SportsDrive() );
}
}
class NormalVehicle extends Vehicle {
NormalVehicle() {
super( new NormalDrive() );
}
}
//stategy pattern- Family of algorithms
interface DriveStrategy {
public void drive();
}
class SportsDrive implements DriveStrategy {
@Override
public void drive() {
System.out.println("Sports Drive Capabilities!!!");
}
}
class NormalDrive implements DriveStrategy {
@Override
public void drive() {
System.out.println("Normal Drive Capabilities!!!");
}
}
public class StrategyDesignPattern {
public static void main(String[] args) {
Vehicle offROadVehicle = new OffRoadVehicle();
offROadVehicle.drive();
Vehicle normalVehicle = new NormalVehicle();
normalVehicle.drive();
}
}
// Applicability:
// 1. Use the Strategy pattern when you want to use different variants of an algorithm within an object and be
// able to switch from one algorithm to another during runtime.
// 2. Use the pattern to isolate the business logic of a class from the
// implementation details of algorithms that may not be as important in the context of that logic.
// 3. Use the pattern when your class has a massive conditional statement that switches between
// different variants of the same algorithm.
// Pros:
// 1. You can isolate the implementation details of an algorithm from the code that uses it.
// 2. Open/Closed Principle. You can introduce new strategies without having to change the context.
// Cons:
// 1. Clients must be aware of the differences between strategies to be able to select a proper one.
// 2. If you only have a couple of algorithms and they rarely change, there’s no real reason to
// overcomplicate the program with new classes and interfaces that come along with the pattern.