Quantcast
Channel: User Filip Milovanović - Software Engineering Stack Exchange
Viewing all articles
Browse latest Browse all 163

Answer by Filip Milovanović for Decoupling command and receiver in command pattern

$
0
0

I presume from your description that all of the commands in the list refer to the same object (car). E.g., it's a small script for a car.

You don't actually need to create the commands right then when you read the file. Instead, for each command, produce, on the fly, a factory function that creates the command when given a car. You can then return a list of these, or you can wrap this list into a top level function that just does

// ...// parse your text file, produce a 'factoryFunctions' list...// I.e. // factoryFunctions.push((car) => new MoveCommand(car));      // "TURN"// factoryFunctions.push((car) => new TurnCommand(car, TurnDirection.LEFT)); // "TURN LEFT"// ...const scriptFactory = (car: Car) => factoryFunctions.map(f => f(car))return scriptFactory

Now you have a thing that takes a Car parameter and creates your script (a list of commands) on-demand that you can pass around in your application. So pass it to something that has access to the Car instance of your choice (cause it's usable with different cars), and make your Invoker accept a Command array:

// client // ('scriptFactory' is injected as a dependency, or is otherwise made accessible)const car = new Car();const invoker = new Invoker(scriptFactory(car));invoker.move()

Viewing all articles
Browse latest Browse all 163

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>