Command Pattern

Behavioral

What is it?

Turns a request into a stand-alone object that contains all the information about the request. This allows for parameterizing clients with queues, requests, and operations.

Why use it?

The Command pattern encapsulates a request as an object, thereby allowing you to parameterize clients with queues, requests, and operations. This is useful for implementing undo/redo operations, queuing tasks, or logging changes. Each command object implements a standard interface and contains logic to execute and possibly reverse an action.

Code Example

typescript
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// Command Pattern Example

// Command Interface
class Command {
  execute() {
    throw new Error('Execute method must be implemented');
  }
  
  undo() {
    throw new Error('Undo method must be implemented');
  }
}

// Receiver - Text Editor
class TextEditor {
  constructor() {
    this.content = '';
    this.clipboard = '';
  }
  
  write(text) {
    this.content += text;
  }
  
  delete(length) {
    this.content = this.content.substring(0, this.content.length - length);
  }
  
  copy(start, end) {
    this.clipboard = this.content.substring(start, end);
  }
  
  paste(position) {
    this.content = this.content.slice(0, position) + 
                   this.clipboard + 
                   this.content.slice(position);
  }
  
  getContent() {
    return this.content;
  }
}

// Concrete Commands
class WriteCommand extends Command {
  constructor(receiver, text) {
    super();
    this.receiver = receiver;
    this.text = text;
  }
  
  execute() {
    this.receiver.write(this.text);
    console.log(`Executed: Write "${this.text}"`);
  }
  
  undo() {
    this.receiver.delete(this.text.length);
    console.log(`Undone: Write "${this.text}"`);
  }
}

class DeleteCommand extends Command {
  constructor(receiver, length) {
    super();
    this.receiver = receiver;
    this.length = length;
    this.deletedText = '';
  }
  
  execute() {
    const content = this.receiver.getContent();
    this.deletedText = content.slice(-this.length);
    this.receiver.delete(this.length);
    console.log(`Executed: Delete ${this.length} characters`);
  }
  
  undo() {
    this.receiver.write(this.deletedText);
    console.log(`Undone: Delete(restored "${this.deletedText}")`);
  }
}

class CopyCommand extends Command {
  constructor(receiver, start, end) {
    super();
    this.receiver = receiver;
    this.start = start;
    this.end = end;
  }
  
  execute() {
    this.receiver.copy(this.start, this.end);
    const copied = this.receiver.getContent().substring(this.start, this.end);
    console.log(`Executed: Copy "${copied}"`);
  }
  
  undo() {
    console.log('Copy operation cannot be undone');
  }
}

class PasteCommand extends Command {
  constructor(receiver, position) {
    super();
    this.receiver = receiver;
    this.position = position;
    this.pastedLength = 0;
  }
  
  execute() {
    const clipboardContent = this.receiver.clipboard;
    this.pastedLength = clipboardContent.length;
    this.receiver.paste(this.position);
    console.log(`Executed: Paste "${clipboardContent}" at position ${this.position}`);
  }
  
  undo() {
    const content = this.receiver.getContent();
    const before = content.slice(0, this.position);
    const after = content.slice(this.position + this.pastedLength);
    this.receiver.content = before + after;
    console.log(`Undone: Paste at position ${this.position}`);
  }
}

// Invoker - Editor Application
class EditorApplication {
  constructor() {
    this.history = [];
    this.currentIndex = -1;
  }
  
  executeCommand(command) {
    // Remove any commands after current index(for redo consistency)
    this.history = this.history.slice(0, this.currentIndex + 1);
    
    // Execute and add to history
    command.execute();
    this.history.push(command);
    this.currentIndex++;
  }
  
  undo() {
    if (this.currentIndex >= 0) {
      const command = this.history[this.currentIndex];
      command.undo();
      this.currentIndex--;
      return true;
    }
    console.log('Nothing to undo');
    return false;
  }
  
  redo() {
    if (this.currentIndex < this.history.length - 1) {
      this.currentIndex++;
      const command = this.history[this.currentIndex];
      command.execute();
      return true;
    }
    console.log('Nothing to redo');
    return false;
  }
}

// Usage
console.log('=== Text Editor Command Example ===');
const editor = new TextEditor();
const app = new EditorApplication();

// Execute commands
app.executeCommand(new WriteCommand(editor, 'Hello '));
app.executeCommand(new WriteCommand(editor, 'World!'));
console.log(`Content: "${editor.getContent()}"\n`);

app.executeCommand(new CopyCommand(editor, 0, 5)); // Copy "Hello"
app.executeCommand(new PasteCommand(editor, 12)); // Paste at end
console.log(`Content: "${editor.getContent()}"\n`);

app.executeCommand(new DeleteCommand(editor, 5)); // Delete "Hello"
console.log(`Content: "${editor.getContent()}"\n`);

// Undo operations
console.log('--- Undoing operations ---');
app.undo(); // Undo delete
console.log(`Content: "${editor.getContent()}"`);

app.undo(); // Undo paste
console.log(`Content: "${editor.getContent()}"`);

app.undo(); // Undo copy(no effect)
app.undo(); // Undo "World!"
console.log(`Content: "${editor.getContent()}"\n`);

// Redo operations
console.log('--- Redoing operations ---');
app.redo(); // Redo "World!"
console.log(`Content: "${editor.getContent()}"`);

app.redo(); // Redo copy
app.redo(); // Redo paste
console.log(`Content: "${editor.getContent()}"\n`);

// Smart Home Command Example
class Light {
  constructor(location) {
    this.location = location;
    this.isOn = false;
    this.brightness = 0;
  }
  
  turnOn() {
    this.isOn = true;
    this.brightness = 100;
    console.log(`${this.location} light is ON(brightness: ${this.brightness}%)`);
  }
  
  turnOff() {
    this.isOn = false;
    this.brightness = 0;
    console.log(`${this.location} light is OFF`);
  }
  
  dim(level) {
    this.brightness = level;
    console.log(`${this.location} light dimmed to ${level}%`);
  }
}

class Fan {
  constructor(location) {
    this.location = location;
    this.isOn = false;
    this.speed = 0;
  }
  
  turnOn() {
    this.isOn = true;
    this.speed = 3;
    console.log(`${this.location} fan is ON(speed: ${this.speed})`);
  }
  
  turnOff() {
    this.isOn = false;
    this.speed = 0;
    console.log(`${this.location} fan is OFF`);
  }
  
  setSpeed(speed) {
    this.speed = speed;
    console.log(`${this.location} fan speed set to ${speed}`);
  }
}

// Smart Home Commands
class LightOnCommand extends Command {
  constructor(light) {
    super();
    this.light = light;
  }
  
  execute() {
    this.light.turnOn();
  }
  
  undo() {
    this.light.turnOff();
  }
}

class LightOffCommand extends Command {
  constructor(light) {
    super();
    this.light = light;
  }
  
  execute() {
    this.light.turnOff();
  }
  
  undo() {
    this.light.turnOn();
  }
}

class DimLightCommand extends Command {
  constructor(light, level) {
    super();
    this.light = light;
    this.level = level;
    this.previousLevel = 0;
  }
  
  execute() {
    this.previousLevel = this.light.brightness;
    this.light.dim(this.level);
  }
  
  undo() {
    this.light.dim(this.previousLevel);
  }
}

class FanOnCommand extends Command {
  constructor(fan) {
    super();
    this.fan = fan;
  }
  
  execute() {
    this.fan.turnOn();
  }
  
  undo() {
    this.fan.turnOff();
  }
}

// Macro Command - Execute multiple commands
class MacroCommand extends Command {
  constructor(commands) {
    super();
    this.commands = commands;
  }
  
  execute() {
    console.log('Executing macro command...');
    this.commands.forEach(cmd => cmd.execute());
  }
  
  undo() {
    console.log('Undoing macro command...');
    // Undo in reverse order
    for (let i = this.commands.length - 1; i >= 0; i--) {
      this.commands[i].undo();
    }
  }
}

// Remote Control
class RemoteControl {
  constructor() {
    this.commands = {};
    this.lastCommand = null;
  }
  
  setCommand(slot, command) {
    this.commands[slot] = command;
  }
  
  pressButton(slot) {
    if (this.commands[slot]) {
      this.commands[slot].execute();
      this.lastCommand = this.commands[slot];
    } else {
      console.log(`No command set for slot ${slot}`);
    }
  }
  
  pressUndo() {
    if (this.lastCommand) {
      this.lastCommand.undo();
    } else {
      console.log('No command to undo');
    }
  }
}

// Usage
console.log('\n=== Smart Home Command Example ===');
const livingRoomLight = new Light('Living Room');
const bedroomLight = new Light('Bedroom');
const ceilingFan = new Fan('Living Room');

const remote = new RemoteControl();

// Set up commands
remote.setCommand(1, new LightOnCommand(livingRoomLight));
remote.setCommand(2, new LightOffCommand(livingRoomLight));
remote.setCommand(3, new DimLightCommand(livingRoomLight, 50));
remote.setCommand(4, new FanOnCommand(ceilingFan));

// Create a "Party Mode" macro
const partyMode = new MacroCommand([
  new LightOnCommand(livingRoomLight),
  new LightOnCommand(bedroomLight),
  new DimLightCommand(livingRoomLight, 30),
  new FanOnCommand(ceilingFan)
]);
remote.setCommand(5, partyMode);

// Use the remote
console.log('--- Using remote control ---');
remote.pressButton(1); // Living room light on
remote.pressButton(3); // Dim to 50%
remote.pressButton(4); // Fan on
remote.pressUndo();    // Fan off

console.log('\n--- Activating party mode ---');
remote.pressButton(5); // Execute macro

console.log('\n--- Ending party mode ---');
remote.pressUndo(); // Undo entire macro

Quick Facts

Category
Behavioral
Common Use Cases
Communication patterns, algorithms

Other Behavioral Patterns