Skip to content

Commit 000993e

Browse files
committed
update
1 parent 8c2fcd0 commit 000993e

168 files changed

Lines changed: 2355 additions & 1071 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

Home.md

Lines changed: 0 additions & 9 deletions
This file was deleted.

design-patterns/behavior (поведенческие)/Command (команда).md

Lines changed: 0 additions & 1 deletion
This file was deleted.

design-patterns/behavior (поведенческие)/Сhain of responsibility (цепочка обязанностей).md renamed to design-patterns/behavior (поведенческие)/chain of responsibility (цепочка обязанностей).md

File renamed without changes.
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
```js
2+
// Command: интерфейс команды
3+
class BankCommand {
4+
execute() {}
5+
undo() {}
6+
}
7+
8+
// ConcreteCommand: операции с балансом
9+
class DepositCommand extends BankCommand {
10+
constructor(account, amount) {
11+
super();
12+
this.account = account;
13+
this.amount = amount;
14+
}
15+
16+
execute() {
17+
this.account.balance += this.amount;
18+
console.log(`Пополнение на ${this.amount}. Текущий баланс: ${this.account.balance}`);
19+
}
20+
21+
undo() {
22+
this.account.balance -= this.amount;
23+
console.log(`Отмена пополнения. Баланс: ${this.account.balance}`);
24+
}
25+
}
26+
27+
class WithdrawCommand extends BankCommand {
28+
constructor(account, amount) {
29+
super();
30+
this.account = account;
31+
this.amount = amount;
32+
}
33+
34+
execute() {
35+
if (this.account.balance >= this.amount) {
36+
this.account.balance -= this.amount;
37+
console.log(`Снятие ${this.amount}. Баланс: ${this.account.balance}`);
38+
} else {
39+
console.log("Недостаточно средств!");
40+
}
41+
}
42+
43+
undo() {
44+
this.account.balance += this.amount;
45+
console.log(`Отмена снятия. Баланс: ${this.account.balance}`);
46+
}
47+
}
48+
49+
// Receiver: банковский счет
50+
class BankAccount {
51+
constructor() {
52+
this.balance = 0;
53+
}
54+
}
55+
56+
// Invoker: обработчик транзакций
57+
class TransactionManager {
58+
constructor() {
59+
this.history = [];
60+
}
61+
62+
execute(command) {
63+
command.execute();
64+
this.history.push(command);
65+
}
66+
67+
undoLast() {
68+
const lastCommand = this.history.pop();
69+
if (lastCommand) {
70+
lastCommand.undo();
71+
}
72+
}
73+
}
74+
75+
// Использование
76+
const account = new BankAccount();
77+
const manager = new TransactionManager();
78+
79+
manager.execute(new DepositCommand(account, 100)); // Пополнение на 100. Баланс: 100
80+
manager.execute(new WithdrawCommand(account, 30)); // Снятие 30. Баланс: 70
81+
manager.undoLast();
82+
```
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
```js
2+
// Command: интерфейс команды
3+
class Command {
4+
execute() {
5+
throw new Error("Method 'execute' must be implemented");
6+
}
7+
8+
undo() {
9+
throw new Error("Method 'undo' must be implemented");
10+
}
11+
}
12+
13+
// ConcreteCommand: конкретные команды
14+
class MoveUpCommand extends Command {
15+
constructor(character) {
16+
super();
17+
this.character = character;
18+
this.prevY = 0;
19+
}
20+
21+
execute() {
22+
this.prevY = this.character.y;
23+
this.character.move(0, -10);
24+
console.log(`Персонаж движется вверх. Новая позиция: (${this.character.x}, ${this.character.y})`);
25+
}
26+
27+
undo() {
28+
this.character.y = this.prevY;
29+
console.log(`Отмена! Персонаж возвращен в позицию: (${this.character.x}, ${this.character.y})`);
30+
}
31+
}
32+
33+
class MoveRightCommand extends Command {
34+
constructor(character) {
35+
super();
36+
this.character = character;
37+
this.prevX = 0;
38+
}
39+
40+
execute() {
41+
this.prevX = this.character.x;
42+
this.character.move(10, 0);
43+
console.log(`Персонаж движется вправо. Новая позиция: (${this.character.x}, ${this.character.y})`);
44+
}
45+
46+
undo() {
47+
this.character.x = this.prevX;
48+
console.log(`Отмена! Персонаж возвращен в позицию: (${this.character.x}, ${this.character.y})`);
49+
}
50+
}
51+
52+
// Receiver: получатель команд (игровой персонаж)
53+
class Character {
54+
constructor() {
55+
this.x = 0;
56+
this.y = 0;
57+
}
58+
59+
move(dx, dy) {
60+
this.x += dx;
61+
this.y += dy;
62+
}
63+
}
64+
65+
// Invoker: инициатор команд (управление вводом + история)
66+
class InputHandler {
67+
constructor() {
68+
this.commands = [];
69+
this.history = [];
70+
}
71+
72+
setCommand(command) {
73+
this.commands.push(command);
74+
}
75+
76+
executeCommand(index) {
77+
if (this.commands[index]) {
78+
this.commands[index].execute();
79+
this.history.push(this.commands[index]);
80+
}
81+
}
82+
83+
undoLastCommand() {
84+
const lastCommand = this.history.pop();
85+
if (lastCommand) {
86+
lastCommand.undo();
87+
}
88+
}
89+
}
90+
91+
// Использование
92+
const character = new Character();
93+
const inputHandler = new InputHandler();
94+
95+
// Назначаем команды на кнопки (0 - вверх, 1 - вправо)
96+
inputHandler.setCommand(new MoveUpCommand(character));
97+
inputHandler.setCommand(new MoveRightCommand(character));
98+
99+
// Игрок нажимает "Вверх" → "Вправо" → "Отмена"
100+
inputHandler.executeCommand(0); // Персонаж движется вверх. Новая позиция: (0, -10)
101+
inputHandler.executeCommand(1); // Персонаж движется вправо. Новая позиция: (10, -10)
102+
inputHandler.undoLastCommand(); // Отмена! Персонаж возвращен в позицию: (0, -10)
103+
```
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
```js
2+
// Command: интерфейс команды
3+
class Command {
4+
execute() {}
5+
undo() {}
6+
}
7+
8+
// ConcreteCommand: команды для устройств
9+
class TurnOnCommand extends Command {
10+
constructor(device) {
11+
super();
12+
this.device = device;
13+
}
14+
15+
execute() {
16+
this.device.turnOn();
17+
}
18+
19+
undo() {
20+
this.device.turnOff();
21+
}
22+
}
23+
24+
class TurnOffCommand extends Command {
25+
constructor(device) {
26+
super();
27+
this.device = device;
28+
}
29+
30+
execute() {
31+
this.device.turnOff();
32+
}
33+
34+
undo() {
35+
this.device.turnOn();
36+
}
37+
}
38+
39+
// Receiver: устройства (лампочка, телевизор)
40+
class Light {
41+
turnOn() {
42+
console.log("Свет включен");
43+
}
44+
45+
turnOff() {
46+
console.log("Свет выключен");
47+
}
48+
}
49+
50+
class TV {
51+
turnOn() {
52+
console.log("Телевизор включен");
53+
}
54+
55+
turnOff() {
56+
console.log("Телевизор выключен");
57+
}
58+
}
59+
60+
// Invoker: пульт управления
61+
class RemoteControl {
62+
constructor() {
63+
this.commands = [];
64+
this.history = [];
65+
}
66+
67+
addCommand(command) {
68+
this.commands.push(command);
69+
}
70+
71+
pressButton(index) {
72+
if (this.commands[index]) {
73+
this.commands[index].execute();
74+
this.history.push(this.commands[index]);
75+
}
76+
}
77+
78+
pressUndo() {
79+
const lastCommand = this.history.pop();
80+
if (lastCommand) {
81+
lastCommand.undo();
82+
}
83+
}
84+
}
85+
86+
// Использование
87+
const light = new Light();
88+
const tv = new TV();
89+
90+
const remote = new RemoteControl();
91+
remote.addCommand(new TurnOnCommand(light)); // Кнопка 0: включить свет
92+
remote.addCommand(new TurnOffCommand(tv)); // Кнопка 1: выключить телевизор
93+
94+
remote.pressButton(0); // Свет включен
95+
remote.pressButton(1); // Телевизор выключен
96+
remote.pressUndo(); // Телевизор включен (отмена последней команды)
97+
```
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
![[files/Pasted image 20240721103022.png]]
2+
3+
Паттерн Command инкапсулирует запрос как объект, позволяя параметризовать клиенты с различными запросами, ставить запросы в очередь или поддерживать отмену операций.
4+
5+
Когда использовать паттерн Command?
6+
- Нужна отмена операций (например, редакторы, игры, банковские приложения).
7+
- Очередь команд (например, планировщик задач).
8+
- Параметризация действий (например, кнопки в GUI с разным поведением).
9+
Преимущества
10+
- Разделение отправителя и получателя (кто вызывает команду и кто её выполняет).
11+
- Гибкость — можно добавлять новые команды без изменения существующего кода.
12+
- Поддержка отмены и повтора операций.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)