-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrategy_pattern_02.html
99 lines (86 loc) · 2.06 KB
/
strategy_pattern_02.html
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
99
<!DOCTYPE html>
<html>
<head>
<title>Strategy Pattern Principle</title>
<style type="text/css">
body{
max-width: 760px;
color: #364f6b;
}
p{
font-size:1rem;
text-align: center;
border: 1px;
font-weight: bold;
color: #364f6b;
margin: 2px;
}
h1{
text-align: center;
font-size: 2rem;
color: black;
}
</style>
</head>
<body>
<h1>Strategy Pattern Principle </h1>
<div>
Here you pass different algorithm or strategy or actions as functions argument in class and then get the result by using
the strategy based on your choice. In the following example, you pass any of the action (addition, substraction, multiply and divide) as function argument and derive the result of two numbers.
</div>
<div>
<p id="add" > </p>
<p id="substract" > </p>
<p id="multiply" > </p>
<p id="divide" > </p>
</div>
<!-- javascript -->
<script type="text/javascript">
/**
* write the strategy as JSON object
* Eements of this json object are functions.
*/
var strategy ={
"Addition": function (a,b){
return a+b;
},
"Substraction": function (a,b){
return a-b;
}
"Multiplication": function (a,b){
return a*b;
}
"Division" : function (a,b){
return a/b
}
}
//Define context
context = fucntion (key, a, b){
return strategy[key](a,b)
}
/**
* @strategy: Addition
*/
var result = context.calculate(4,2);
document.getElementById("add").innerHTML= "Addition: "+result ;
/**
@Strategy: Substraction
*/
context = new Context(new Substraction);
result = context.calculate(4,2)
document.getElementById("substract").innerHTML ="Substraction: "+result;
/**
@Strategy: Divide
*/
context = new Context(new Division);
result = context.calculate(4,2)
document.getElementById("divide").innerHTML ="Division: "+result;
/**
@Strategy: Multiplication
*/
context = new Context(new Multiplication);
result = context.calculate(4,2)
document.getElementById("multiply").innerHTML ="Multiplication: "+result;
</script>
</body>
</html>