-
Notifications
You must be signed in to change notification settings - Fork 1
/
MethodChain.java
115 lines (93 loc) · 2.82 KB
/
MethodChain.java
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Method chain
package behavioral.chainofresponsibility;
class Creature
{
public String name;
public int attack, defense;
public Creature(String name, int attack, int defense) {
this.name = name;
this.attack = attack;
this.defense = defense;
}
@Override
public String toString() {
return "Creature{" +
"name='" + name + '\'' +
", attack=" + attack +
", defense=" + defense +
'}';
}
}
// Modifier here - base constructor
class CreatureModifier
{
protected Creature creature;
protected CreatureModifier next; // linked list-like approach?
public CreatureModifier(Creature creature) {
this.creature = creature;
}
public void add(CreatureModifier cm)
{
if(next != null)
{
next.add(cm); //recursive call on the next object until next == null
}
else next = cm;
}
public void handle()
{
if (next != null) next.handle(); // call handle on the entire chain
}
}
class DoubleAttackModifier extends CreatureModifier
{
public DoubleAttackModifier(Creature creature) {
super(creature);
}
@Override
public void handle() {
System.out.println("Doubling " + creature.name + "'s attack");
creature.attack *= 2;
super.handle(); // this is critical to handle the chain of handlers
}
}
class IncreaseDefenseModifier extends CreatureModifier
{
public IncreaseDefenseModifier(Creature creature) {
super(creature);
}
@Override
public void handle() {
System.out.println("Increasing " + creature.name + "'s defense");
creature.defense += 3;
super.handle();
}
}
// HOW TO INTERRUPT CHAIN OF RESPONSIBILITY
class NoBonusesModifier extends CreatureModifier
{
public NoBonusesModifier(Creature creature) {
super(creature);
}
@Override
public void handle() {
//nothing - don't call super.handle() to interrupt chain after this one is called
System.out.println("No bonuses for you!");
}
}
class MethodChainDemo
{
public static void main(String[] args) {
Creature goblin = new Creature("Goblin", 2, 2);
System.out.println(goblin);
// Instantiate root class of CreatureModifier as a starting point
CreatureModifier root = new CreatureModifier(goblin);
System.out.println("Let's double goblin's attack");
root.add(new DoubleAttackModifier(goblin));
root.add(new NoBonusesModifier(goblin)); // Subverts the chain of responsibility
System.out.println("Let's increase goblin's defense");
root.add(new IncreaseDefenseModifier(goblin));
root.handle(); // THIS is what traverses chain of responsibility
System.out.println(goblin);
}
}