-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrategyTest.java
More file actions
98 lines (76 loc) · 2.15 KB
/
StrategyTest.java
File metadata and controls
98 lines (76 loc) · 2.15 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
92
93
94
95
96
97
98
/*
A Behavioral Pattern.
The Strategy pattern is very useful for situations where you would like
to dynamically swap the algorithms used in an application. If you think
of an algorithm as a strategy for accomplishing some task, you can begin
to imagine ways to use Strategy. Strategy is intended to provide you with
a means to define a family of algorithms, encapsulate each one as an object,
and make them interchangeable. Strategy lets the algorithms vary independently
from clients that use them.
*/
public class StrategyTest {
public static void main(String[] args){
System.out.println("-------------- STRATEGY ---------------");
Calculator calculator = new Calculator();
calculator.setA(10.0);
calculator.setB(3);
calculator.setMethod(new Addition());
calculator.calculate();
calculator.setMethod(new Subtraction());
calculator.calculate();
calculator.setMethod(new Multiplication());
calculator.calculate();
calculator.setMethod(new Division());
calculator.calculate();
}
}
// Context
class Calculator {
double a, b;
CalculationMethod method = null;
Calculator(){}
public void setA(double n){
a = n;
}
public void setB(double n){
b = n;
}
public void setMethod(CalculationMethod m){
method = m;
}
public void calculate(){
if(method == null){
System.out.println("Please specify a calculation method.");
return;
}
System.out.println(method.getClass().getName()+" of "+a+" and "+b+" = "+method.execute(a, b));
}
};
// Strategy
interface CalculationMethod {
public double execute(double a, double b);
};
// Strategy 1
class Addition implements CalculationMethod {
public double execute(double a, double b){
return a+b;
}
};
// Strategy 2
class Division implements CalculationMethod {
public double execute(double a, double b){
return a/b;
}
};
// Strategy 3
class Subtraction implements CalculationMethod {
public double execute(double a, double b){
return a-b;
}
};
// Strategy 4
class Multiplication implements CalculationMethod {
public double execute(double a, double b){
return a*b;
}
};