/
index.ts
51 lines (43 loc) · 1.3 KB
/
index.ts
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
// https://en.wikipedia.org/wiki/Visitor_pattern
namespace VisitorPattern {
interface Visitor {
visitElementA(element: ElementA): void;
visitElementB(element: ElementB): void;
}
class ConcreteVisitor implements Visitor {
public visitElementA(element: ElementA): void {
console.log("`visitElementA` of ConcreteVisitor is being called!");
}
public visitElementB(element: ElementB): void {
console.log("`visitElementB` of ConcreteVisitor is being called!");
}
}
interface Element {
accept(visitor: Visitor): void;
}
class ElementA implements Element {
public accept(visitor: Visitor): void {
console.log("`accept` of ElementA is being called!");
visitor.visitElementA(this);
}
}
class ElementB implements Element {
public accept(visitor: Visitor): void {
console.log("`accept` of ElementB is being called!");
visitor.visitElementB(this);
}
}
// Client code
var elements = [new ElementA(), new ElementB()];
var visitor = new ConcreteVisitor();
elements.forEach((e) => {
e.accept(visitor);
});
// Output
/*
`accept` of ElementA is being called!
`visitElementA` of ConcreteVisitor is being called!
`accept` of ElementB is being called!
`visitElementB` of ConcreteVisitor is being called!
*/
}