可将请求转换为一个包含与请求相关的所有信息的独立对象。 该转换让你能根据不同的请求将方法参数化、延迟请求执行或将其放入队列中,且能实现可撤销操作。
实现方式
声明仅有一个执行方法的命令接口
/**
* The Command interface declares a method for executing a command.
*/
interface Command {
execute(): void;
}
抽取请求并使之成为实现命令接口的具体命令类。每个类都必须有一组成员变量来保存请求参数和对于实际接收者对象的引用。所有这些变量的数值都必须通过命令构造函数进行初始化 ```typescript /**
Some commands can implement simple operations on their own. */ class SimpleCommand implements Command { private payload: string;
constructor(payload: string) { this.payload = payload; }
public execute(): void { console.log(
SimpleCommand: See, I can do simple things like printing (${this.payload})
); } }
/**
- However, some commands can delegate more complex operations to other objects,
called “receivers.” */ class ComplexCommand implements Command { private receiver: Receiver;
/**
Context data, required for launching the receiver’s methods. */ private a: string;
private b: string;
/**
- Complex commands can accept one or several receiver objects along with
any context data via the constructor. */ constructor(receiver: Receiver, a: string, b: string) { this.receiver = receiver; this.a = a; this.b = b; }
/**
- Commands can delegate to any methods of a receiver. */ public execute(): void { console.log(‘ComplexCommand: Complex stuff should be done by a receiver object.’); this.receiver.doSomething(this.a); this.receiver.doSomethingElse(this.b); } } ```
找到担任发送者职责的类。在这些类中添加保存命令的成员变量。发送者只能通过命令接口与其命令进行交互。发送者自身通常并不创建命令对象,而是通过客户端代码获取 ```typescript /**
- The Receiver classes contain some important business logic. They know how to
- perform all kinds of operations, associated with carrying out a request. In
fact, any class may serve as a Receiver. */ class Receiver { public doSomething(a: string): void { console.log(
Receiver: Working on (${a}.)
); }public doSomethingElse(b: string): void { console.log(
Receiver: Also working on (${b}.)
); } }
4. 修改发送者使其执行命令,而非直接将请求发送给接收者
```typescript
/**
* The Invoker is associated with one or several commands. It sends a request to
* the command.
*/
class Invoker {
private onStart: Command;
private onFinish: Command;
/**
* Initialize commands.
*/
public setOnStart(command: Command): void {
this.onStart = command;
}
public setOnFinish(command: Command): void {
this.onFinish = command;
}
/**
* The Invoker does not depend on concrete command or receiver classes. The
* Invoker passes a request to a receiver indirectly, by executing a
* command.
*/
public doSomethingImportant(): void {
console.log('Invoker: Does anybody want something done before I begin?');
if (this.isCommand(this.onStart)) {
this.onStart.execute();
}
console.log('Invoker: ...doing something really important...');
console.log('Invoker: Does anybody want something done after I finish?');
if (this.isCommand(this.onFinish)) {
this.onFinish.execute();
}
}
private isCommand(object): object is Command {
return object.execute !== undefined;
}
}
- 客户端必须按照以下顺序来初始化对象:
- 创建接收者
- 创建命令,如有需要可将其关联至接收者
- 创建发送者并将其与特定命令关联 ```typescript /**
- The client code can parameterize an invoker with any commands. */ const invoker = new Invoker(); invoker.setOnStart(new SimpleCommand(‘Say Hi!’)); const receiver = new Receiver(); invoker.setOnFinish(new ComplexCommand(receiver, ‘Send email’, ‘Save report’));
invoker.doSomethingImportant();
<a name="lxHcw"></a>
# 实例
<a name="RZZ4n"></a>
## 自定义快捷键
```typescript
interface Command {
exec(): void
}
class CopyCommand implements Command {
editor: Editor
constructor(editor: Editor) {
this.editor = editor
}
exec() {
const { editor } = this
editor.clipboard = editor.text.slice(...editor.range)
}
}
class CutCommand implements Command {
editor: Editor
constructor(editor: Editor) {
this.editor = editor
}
exec() {
const { editor } = this
editor.clipboard = editor.text.slice(...editor.range)
editor.text = editor.text.slice(0, editor.range[0]) + editor.text.slice(editor.range[1])
}
}
class PasteCommand implements Command {
editor: Editor
constructor(editor: Editor) {
this.editor = editor
}
exec() {
const { editor } = this
editor.text = editor.text.slice(0, editor.cursorIndex) + editor.clipboard + editor.text.slice(editor.cursorIndex)
}
}
type Editor = {
cursorIndex: number;
range: [number, number];
text: string;
clipboard: string;
}
const editor: Editor = {
cursorIndex: 0,
range: [0, 1],
text: 'some text',
clipboard: ''
}
type Keymap = { [key: string]: Command }
class Hotkey {
keymap: Keymap = {}
constructor(keymap: Keymap) {
this.keymap = keymap
}
call(e: KeyboardEvent) {
const prefix = e.ctrlKey ? 'ctrl+' : ''
const key = prefix + e.key
this.dispatch(key)
}
dispatch(key: string) {
this.keymap[key].exec()
}
}
const keymap = {
'ctrl+x': new CutCommand(editor),
'ctrl+c': new CopyCommand(editor),
'ctrl+v': new PasteCommand(editor)
}
const hotkey = new Hotkey(keymap)
document.onkeydown = (e) => {
hotkey.call(e)
}
上面的 hotkey 是 Invoker,editor 是 Receiver。
Redux 也是应用了命令模式,Store 相当于 Receiver,Action 相当于 Command,Dispatch 相当于 Invoker