-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrategy_operation_example.dart
55 lines (44 loc) · 1.27 KB
/
strategy_operation_example.dart
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
/// Step 1: Create an interface.
abstract interface class Strategy {
int doOperation(int num1, int num2);
}
///
/// Step 2: Create concrete classes implementing the same interface.
/// OperationAdd
class OperationAdd implements Strategy {
@override
int doOperation(int num1, int num2) => num1 + num2;
}
/// OperationSubtract
class OperationSubtract implements Strategy {
@override
int doOperation(int num1, int num2) => num1 - num2;
}
/// OperationMultiply
class OperationMultiply implements Strategy {
@override
int doOperation(int num1, int num2) => num1 * num2;
}
///
/// Step 3: Create Context Class.
class Context {
final Strategy _strategy;
Context(Strategy strategy) : _strategy = strategy;
int executeStrategy(int num1, int num2) {
return _strategy.doOperation(num1, num2);
}
}
///
/// Step 4: Use the Context to see change in behavior when it changes its Strategy.
void main() {
Context context = Context(OperationAdd());
print("10 + 5 = ${context.executeStrategy(10, 5)}");
context = Context(OperationSubtract());
print("10 - 5 = ${context.executeStrategy(10, 5)}");
context = Context(OperationMultiply());
print("10 * 5 = ${context.executeStrategy(10, 5)}");
}
/// Step 5: Verify the output.
// 10 + 5 = 15
// 10 - 5 = 5
// 10 * 5 = 50