-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathVisitor.dart
80 lines (60 loc) · 1.92 KB
/
Visitor.dart
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
import 'package:design_pattern_dart/Display/Example.dart';
class Visitor extends Example {
Visitor([String filePath = "lib/Behavioral/Visitor.dart"]) : super(filePath);
@override
String testRun() {
Animal monkey = Monkey();
Animal lion = Lion();
Animal dolphin = Dolphin();
var speak = Speak();
var jump = Jump();
return """
Monkey speak: ${speak.visitMonkey(monkey)}
Dolphin speak: ${speak.visitDolphin(dolphin)}
Lion jump: ${jump.visitLion(lion)}
""";
}
}
abstract class Animal {
String accept(AnimalOperation operation);
}
abstract class AnimalOperation {
String visitMonkey(Monkey monkey);
String visitLion(Lion lion);
String visitDolphin(Dolphin dolphin);
}
// 各種動物的基本 Class ,我們想盡量不再動到他們
class Monkey implements Animal {
String shout() => 'Ooh oo aa aa!';
@override
String accept(AnimalOperation operation) => operation.visitMonkey(this);
}
class Lion implements Animal {
String roar() => 'Roaaar';
@override
String accept(AnimalOperation operation) => operation.visitLion(this);
}
class Dolphin implements Animal {
String speak() => 'Tuut tuttu tuutt!';
@override
String accept(AnimalOperation operation) => operation.visitDolphin(this);
}
// 利用 AnimalOperation 製造動物們 "Speak" 的 operation
class Speak implements AnimalOperation {
@override
String visitMonkey(Monkey monkey) => monkey.shout();
@override
String visitDolphin(Dolphin dolphin) => dolphin.speak();
@override
String visitLion(Lion lion) => lion.roar();
}
// 過了幾天,想再幫動物加入 "jump" 的 operation
class Jump implements AnimalOperation {
@override
String visitDolphin(Dolphin dolphin) =>
"Walked on water a little and disappeared";
@override
String visitLion(Lion lion) => 'Jumped 7 feet! Back on the ground!';
@override
String visitMonkey(Monkey monkey) => "Jumped 20 feet high! on to the tree!";
}