File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
Design Pattern in JavaScript Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
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!"
You can’t perform that action at this time.
0 commit comments