-1

Suppose you need to implement a toy VM(such for Brainfuck) where you have an external data structure representing the memory(a simple fixed array), and a ComputationalUnit object which cares of acting operations from a given set. What is the most efficient way to implement the last to make easy adding instruction, other than a giant switch calling the right method given the instruction. Assume instruction are read from a file or from user input as a String or char(brainfuck case) or by regret parsing.

If the answer involves a design pattern, I would be pleased to be redirected. Thanks to all.

NB: I’m asking for a structure, Java is not an issue

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
majik
  • 128
  • 9

1 Answers1

1

Generally a giant switch is the way to go.

You may wrap instructions into classes, give them access to memory/registers and implement something like execute(some context) - thus adding instructions will be reduced to adding new classes. Of course, you will need a kind of instruction parser, in this approach the parser must be somehow initialized based on the list of available instructions.

You may use the approach, similar to what HW developers do - make an analogue of a microcode - split VM instuctions into smaller actions and process these actions in a smaller switch, e.g. loading a value from memory to stack can be split into 2 operations - loading some data from memory into temporary register and pushing this register to stack - each operation can be later reused.

ekaerovets
  • 1,158
  • 10
  • 18