forked from chuanxshi/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisitor.html
More file actions
92 lines (74 loc) · 1.92 KB
/
visitor.html
File metadata and controls
92 lines (74 loc) · 1.92 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
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: Visitor
Description: Represent an operation to be performed on the elements of an object structure.
Visitor lets you define a new operation without changing the classes of the elements on which it operates.
*/
var Employee = function (name, salary, vacation) {
var self = this;
this.accept = function (visitor) {
visitor.visit(self);
};
this.getName = function () {
return name;
};
this.getSalary = function () {
return salary;
};
this.setSalary = function (sal) {
salary = sal;
};
this.getVacation = function () {
return vacation;
};
this.setVacation = function (vac) {
vacation = vac;
};
};
var ExtraSalary = function () {
this.visit = function (emp) {
emp.setSalary(emp.getSalary() * 1.1);
};
};
var ExtraVacation = function () {
this.visit = function (emp) {
emp.setVacation(emp.getVacation() + 2);
};
};
// log helper
var log = (function() {
var log = "";
return {
add: function(msg) { log += msg + "\n"; },
show: function() { alert(log); log = ""; }
}
})();
//example
function run() {
var employees = [
new Employee("John", 10000, 10),
new Employee("Mary", 20000, 21),
new Employee("Boss", 250000, 51)
];
var visitorSalary = new ExtraSalary();
var visitorVacation = new ExtraVacation();
for (var i = 0, len = employees.length; i < len; i++) {
var emp = employees[i];
emp.accept(visitorSalary);
emp.accept(visitorVacation);
log.add(emp.getName() + ": $" + emp.getSalary() +
" and " + emp.getVacation() + " vacation days");
}
log.show();
}
// reference
// http://www.dofactory.com/javascript/visitor-design-pattern
</script>
</body>
</html>