In this video, Reynald guides you in the process of coding what’s left and required on the client side to execute the program. He then demonstrates the finished code by running it and providing a summary of the results. The intent of this exercise is to provide you a chance think through and see how all the pieces come together for the Interpreter pattern.
- [Voiceover] Okay, so we're ready to code our client for the interpreter pattern. And the first thing I'm going to do is, I'm going to collapse my client class, and within my main method, we'll start off indicating what Roman numeral we're going to translate. So, define Roman as, I'll say, MMXVII, and that's the current year, 2017.
And now, we need to set our context. So let's go ahead and set that variable, and create a new instance of a context, and pass in our Roman numeral. Next is to build the tree to parse. Build the parse tree. And we'll start off by creating a list of expression, and create this new list instance, and then begin adding to it.
And we'll start off with a new instance of ThousandExpression, and we will do the same for the remainder, that is hundred, ten, and one. Next is to interpret everything in this tree.
So let's go ahead and do a for each expression. I can just use this method stub here, highlight foreach and hit tab, tab, and now I can just type in expression, tab over, and I'll just say exp, and for the collection that is in our tree. Alright, enter. For every expression we want to invoke the interpret for the current context.
And then we will write it out to the console. And what we'll do is, write out using some string interpolation, the Roman numeral that we asked to be interpreted is equal to the value that it actually outputted from our context.
Alright? The last thing is to just wait for the user. That is, to pause the screen. Okay, I'll save, looks good. Let's go ahead and hit the green button to execute. And there we go, Roman numeral MMXVII is equal to 2017.
And if we wanted to double-check this, there's actually a website here that we can enter in a numerical value. 2017, MMXVII. So, the interpreter pattern is really for when you're in a situation that requires lots of work, that you think is essentially translation. That is, there's a need to interpret a grammar that can be represented as a syntax tree, to conduct interpretation, as we just did for converting a Roman numeral to decimal.
- What are design patterns?
- Who are the Gang of Four?
- Learning about the three categories of design patterns
- Builder pattern
- Adapter pattern
- Composite pattern
- Chain of Responsibility pattern
- Command pattern
- Interpreter pattern
- Mediator pattern
- Visitor pattern