The Command Pattern
Colyseus has an optional package called @colyseus/command
that implements the Command Pattern. This pattern is useful when you need to decouple the classes that invoke the operation from the object that knows how to execute it.
The command pattern has several advantages, such as:
- It decouples the classes that invoke the operation from the object that knows how to execute the operation.
- It allows you to create a sequence of commands by providing a queue system.
- Implementing extensions to add a new command is easy and can be done without changing the existing code.
- Have strict control over how and when commands are invoked.
- Improves code readability and the possibility of unit testing.
Usage
Installation
npm install --save @colyseus/command
Initialize the dispatcher
in your room implementation:
MyRoom.ts
import { Room } from "colyseus";
import { Dispatcher } from "@colyseus/command";
import { OnJoinCommand } from "./OnJoinCommand";
class MyRoom extends Room<YourState> {
dispatcher = new Dispatcher(this);
onCreate() {
this.setState(new YourState());
}
onJoin(client, options) {
this.dispatcher.dispatch(new OnJoinCommand(), {
sessionId: client.sessionId
});
}
onDispose() {
this.dispatcher.stop();
}
}
How a command implementation looks like:
OnJoinCommand.ts
import { Command } from "@colyseus/command";
export class OnJoinCommand extends Command<MyRoom, {
sessionId: string
}> {
execute({ sessionId }) {
this.state.players[sessionId] = new Player();
}
}
See more
- See command definitions
- See usage
- See implementation
Last updated on