Skip to content

Commit e0f4fb1

Browse files
committed
Codebeispiel für das Strategy Pattern als Entwurfsmuster in JavaScript
1 parent ce2d007 commit e0f4fb1

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Strategy interface
2+
class FightingStrategy {
3+
attack() {}
4+
}
5+
6+
// Concrete Strategy classes
7+
class SwordStrategy extends FightingStrategy {
8+
attack() {
9+
console.log("Elf attacks with a sword!");
10+
}
11+
}
12+
13+
class AxeStrategy extends FightingStrategy {
14+
attack() {
15+
console.log("Dwarf attacks with an axe!");
16+
}
17+
}
18+
19+
class MagicStrategy extends FightingStrategy {
20+
attack() {
21+
console.log("Mage attacks with magic!");
22+
}
23+
}
24+
25+
// Context class
26+
class Character {
27+
constructor(strategy) {
28+
this.strategy = strategy;
29+
}
30+
31+
setStrategy(strategy) {
32+
this.strategy = strategy;
33+
}
34+
35+
attack() {
36+
this.strategy.attack();
37+
}
38+
}
39+
40+
// Usage
41+
const elf = new Character(new SwordStrategy());
42+
const dwarf = new Character(new AxeStrategy());
43+
const mage = new Character(new MagicStrategy());
44+
45+
elf.attack(); // outputs "Elf attacks with a sword!"
46+
dwarf.attack(); // outputs "Dwarf attacks with an axe!"
47+
mage.attack(); // outputs "Mage attacks with magic!"
48+
49+
elf.setStrategy(new MagicStrategy());
50+
elf.attack(); // outputs "Mage attacks with magic!"

0 commit comments

Comments
 (0)