I'm writing a simulation of a car that can receive commands and act on them and I'm trying to implement it using the command pattern.
class Car {
move() {
console.log('move');
}
}
interface Command {
execute():void;
}
// there can be more commands like this. eg: TURN, ACCELERATE
class MoveCommand implements Command {
private car: Car;
constructor(car: Car) {
this.car = car;
}
execute() {
this.car.move();
}
}
class Invoker {
private moveCommand: MoveCommand;
constructor(moveCommand: MoveCommand) {
this.moveCommand = moveCommand;
}
move() {
this.moveCommand.execute();
}
}
The client would issue commands to the car as below.
// client
const car = new Car();
const invoker = new Invoker(new MoveCommand(car));
invoker.move();
I want to modify this so that a series of commands (eg: MOVE, TURN) can be read from a text file and then executed. In this case, a command parser class will convert the text commands to an array of Command objects. I'm having a hard time thinking of a clean way the command parser can create Command objects since the commands need to know about the receiver. It seems that I can remove the receiver from the constructor of MoveCommand and pass it into the execute method instead, or I can have a setter to set the receiver after the Command has been instantiated, but it feels like I'm violating the commonly used standard for the command pattern. Is there a cleaner way to achieve this, or am I trying to use the command pattern in a situation where it doesn't fit in? If the latter is the case, what would be a better design pattern for this scenario?