-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrategyExample01.java
More file actions
59 lines (47 loc) · 1.56 KB
/
StrategyExample01.java
File metadata and controls
59 lines (47 loc) · 1.56 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
/*
context : code that will remain unchanged
behaviour/strategy : code that will change
In the below code, Add and Multiply classes are our strategy. These class will be modified according to the client's wish.
So I have separeted them.On the other hand, Calculator class will not be changed.Suppose now we need a feature of substraction.
We can simply add a class for this feature and it will implement the Operation interface.And for that we don't have to make
modification in Calculator class.We can easily take the advantage of any feature/strategy using Calculator class.
*/
interface Operation{
int performOperation(int num1,int num2);
}
class Add implements Operation{
Operation op;
public int performOperation(int num1,int num2){
return num1+num2;
}
void SetOperation(Operation op){
this.op = op;
}
}
class Multiply implements Operation{
Operation op;
public int performOperation(int num1,int num2){
return num1*num2;
}
void SetOperation(Operation op){
this.op = op;
}
}
class Calculator{
Operation op;
int performOperation(int num1,int num2){
return op.performOperation(num1, num2);
}
void SetOperation(Operation op){
this.op = op;
}
}
public class StrategyExample01 {
public static void main(String[] args) {
Calculator cal = new Calculator();
cal.SetOperation(new Add());
System.out.println(cal.performOperation(10, 20));
cal.SetOperation(new Multiply());
System.out.println(cal.performOperation(10, 20));
}
}