Skip to content

Commit 882f000

Browse files
committed
Add README.
1 parent 80f5783 commit 882f000

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Visitor pattern
2+
Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which
3+
they operate.
4+
5+
Tutorial: [here](https://refactoring.guru/design-patterns/visitor).
6+
7+
### About example.
8+
9+
## Client code:
10+
### Before:
11+
```dart
12+
void main() {
13+
final list = createElements();
14+
list.forEach(operation1);
15+
}
16+
17+
Iterable<Object> createElements() {
18+
return [
19+
One(),
20+
Two(),
21+
Three(),
22+
];
23+
}
24+
25+
void operation1(Object obj) {
26+
if (obj is One) {
27+
print('operation1: one (param1 = ${obj.param1})');
28+
} else if (obj is Two) {
29+
print('operation1: two (param2 = ${obj.param2})');
30+
} else if (obj is Three) {
31+
print('operation1: two (param3 = ${obj.param3})');
32+
}
33+
}
34+
```
35+
36+
### After:
37+
```dart
38+
void main() {
39+
final list = createElements();
40+
41+
for (final e in elements) {
42+
e.accept(visitor);
43+
}
44+
}
45+
46+
Iterable<Object> createElements() {
47+
return [
48+
One(),
49+
Two(),
50+
Three(),
51+
];
52+
}
53+
54+
class ConcreteVisitor1 implements Visitor {
55+
@override
56+
void visitOne(One one) {
57+
print('operation1: one (param1 = ${one.param1})');
58+
}
59+
60+
@override
61+
void visitTwo(Two two) {
62+
print('operation1: two (param2 = ${two.param2})');
63+
}
64+
65+
@override
66+
void visitThree(Three three) {
67+
print('operation1: three (param3 = ${three.param3})');
68+
}
69+
}
70+
```
71+
#### Diagram:
72+
![image](https://user-images.githubusercontent.com/8049534/174583542-5f57463c-148b-4113-acd3-2814ec017ecc.png)
73+
74+
### Output:
75+
```
76+
operation1: one (param1 = 1)
77+
operation1: two (param2 = 2)
78+
operation1: three (param3 = 3)
79+
operation2: one (param1 = 1)
80+
operation2: two (param2 = 2)
81+
operation2: three (param3 = 3)
82+
```

0 commit comments

Comments
 (0)