From f105e32af51580a7ab309940ca29f30a077f21de Mon Sep 17 00:00:00 2001 From: Lauchmelder Date: Sun, 28 Nov 2021 15:28:50 +0100 Subject: [PATCH] refactored instruction creation --- src/parser/instructionFactory.ts | 19 ++++++++++++++++ src/parser/parser.ts | 37 +++++--------------------------- 2 files changed, 24 insertions(+), 32 deletions(-) create mode 100644 src/parser/instructionFactory.ts diff --git a/src/parser/instructionFactory.ts b/src/parser/instructionFactory.ts new file mode 100644 index 0000000..e1e9d5a --- /dev/null +++ b/src/parser/instructionFactory.ts @@ -0,0 +1,19 @@ +/// + +abstract class InstructionFactory +{ + private static symbolDict: { [name: string] : Function } = { + "point": (): PointInstruction => { return new PointInstruction(); }, + "line": (): LineInstruction => { return new LineInstruction(); }, + "circle": (): CircleInstruction => { return new CircleInstruction(); }, + "len": (): LengthInstruction => { return new LengthInstruction(); } + } + + public static createInstruction(name: string): Instruction + { + if(!(name in InstructionFactory.symbolDict)) + return null; + + return InstructionFactory.symbolDict[name](); + } +} \ No newline at end of file diff --git a/src/parser/parser.ts b/src/parser/parser.ts index ee57532..2bce9b4 100644 --- a/src/parser/parser.ts +++ b/src/parser/parser.ts @@ -1,5 +1,5 @@ /// -/// +/// class Parser { @@ -66,38 +66,11 @@ class Parser } params.push(paramlist); - let newInstruction; - switch(symbol) + let newInstruction = InstructionFactory.createInstruction(symbol); + if(newInstruction === null) { - case "point": - { - newInstruction = new PointInstruction(); - break; - } - - case "line": - { - newInstruction = new LineInstruction(); - break; - } - - case "circle": - { - newInstruction = new CircleInstruction(); - break; - } - - case "len": - { - newInstruction = new LengthInstruction(); - break; - } - - default: - { - console.error("Unknown instruction \"" + symbol + "\""); - return null; - } + console.error("Unknown instruction: \"" + symbol + "\""); + return null; } let expectedArgs = newInstruction.getParameterCount();