Strategy pattern and command patternz are very similar. I just want to confirm my understand of their differences.
Can I say with both design patterns, they both require to implement the methods in the interface. The difference is that with command pattern, with the constructor, you have to create the command class, like the below AddThenMultiplyCommand, however, with the strategy pattern, you don't need create the class in the constructor, and when you implement the interface method, you just call the function directly, like AddThenMultiplyStrategy, it calls the add method and multiple method directly without create them in the constructor.
Is my understand correct?
code link: https://codesandbox.io/s/typescript-forked-c64qpw?file=/src/index.ts:0-1915
interface Action {
execute(currentValue: number): number;
}
class AddCommand implements Action {
private valueToAdd;
constructor(valueToAdd: number) {
this.valueToAdd = valueToAdd;
}
execute(currentValue: number) {
return currentValue + this.valueToAdd;
}
}
class MultiplyCommand implements Action {
private valueToMultiply;
constructor(valueToMultiply: number) {
this.valueToMultiply = valueToMultiply;
}
execute(currentValue: number) {
return currentValue * this.valueToMultiply;
}
}
class AddThenMultiplyCommand implements Action {
private addCommand: AddCommand;
private multiplyCommand: MultiplyCommand;
constructor(valueToAdd: number, valueToMultiply: number) {
this.addCommand = new AddCommand(valueToAdd);
this.multiplyCommand = new MultiplyCommand(valueToMultiply);
}
execute(currentValue: number) {
const newValue = this.addCommand.execute(currentValue);
return this.multiplyCommand.execute(newValue);
}
}
class AddThenMultiplyStrategy implements Action {
private valueToAdd;
private valueToMultiply;
constructor(valueToAdd: number, valueToMultiply: number) {
this.valueToAdd = valueToAdd;
this.valueToMultiply = valueToMultiply;
}
execute(currentValue: number) {
// run add
const add = new AddCommand(this.valueToAdd);
// run multiple
const multiple = new MultiplyCommand(this.valueToMultiply);
const newValue = multiple.execute(add.execute(currentValue));
return newValue;
}
}
const add = new AddCommand(5);
console.log(add.execute(6)); // 5+6
const multiple = new MultiplyCommand(5);
console.log(multiple.execute(6)); // 5*6
const addThenMultiplyCommand = new AddThenMultiplyCommand(5, 6);
console.log(addThenMultiplyCommand.execute(5)); // (5+5)*6
const addThenMultiplyStrategy = new AddThenMultiplyStrategy(5, 6);
console.log(addThenMultiplyStrategy.execute(5)); // (5+5)*6