Skip to content

Commit f316260

Browse files
authored
Merge pull request chuanxshi#151 from iamisti/master
adding visitor pattern
2 parents a6aee0a + 1962900 commit f316260

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

design-patterns/visitor.html

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<title>JavaScript Patterns</title>
5+
<meta charset="utf-8">
6+
</head>
7+
<body>
8+
<script>
9+
/* Title: Visitor
10+
Description: Represent an operation to be performed on the elements of an object structure.
11+
Visitor lets you define a new operation without changing the classes of the elements on which it operates.
12+
*/
13+
14+
var Employee = function (name, salary, vacation) {
15+
var self = this;
16+
17+
this.accept = function (visitor) {
18+
visitor.visit(self);
19+
};
20+
21+
this.getName = function () {
22+
return name;
23+
};
24+
25+
this.getSalary = function () {
26+
return salary;
27+
};
28+
29+
this.setSalary = function (sal) {
30+
salary = sal;
31+
};
32+
33+
this.getVacation = function () {
34+
return vacation;
35+
};
36+
37+
this.setVacation = function (vac) {
38+
vacation = vac;
39+
};
40+
};
41+
42+
var ExtraSalary = function () {
43+
this.visit = function (emp) {
44+
emp.setSalary(emp.getSalary() * 1.1);
45+
};
46+
};
47+
48+
var ExtraVacation = function () {
49+
this.visit = function (emp) {
50+
emp.setVacation(emp.getVacation() + 2);
51+
};
52+
};
53+
54+
// log helper
55+
var log = (function() {
56+
var log = "";
57+
58+
return {
59+
add: function(msg) { log += msg + "\n"; },
60+
show: function() { alert(log); log = ""; }
61+
}
62+
})();
63+
64+
//example
65+
function run() {
66+
67+
var employees = [
68+
new Employee("John", 10000, 10),
69+
new Employee("Mary", 20000, 21),
70+
new Employee("Boss", 250000, 51)
71+
];
72+
73+
var visitorSalary = new ExtraSalary();
74+
var visitorVacation = new ExtraVacation();
75+
76+
for (var i = 0, len = employees.length; i < len; i++) {
77+
var emp = employees[i];
78+
79+
emp.accept(visitorSalary);
80+
emp.accept(visitorVacation);
81+
log.add(emp.getName() + ": $" + emp.getSalary() +
82+
" and " + emp.getVacation() + " vacation days");
83+
}
84+
85+
log.show();
86+
}
87+
88+
// reference
89+
// http://www.dofactory.com/javascript/visitor-design-pattern
90+
</script>
91+
</body>
92+
</html>

0 commit comments

Comments
 (0)