The Interpreter Design Pattern was created to solve an issue interpreting data from a context. By having separate classes, one for each type of interpretation, it is possible to have well-defined classes with single purposes.
To do this design our application needs a structure similar to the following:
- Context <-- Client --> Expression1
- `-> Expression2
The client has a context that is sent to a list of expression interpreters and they set the output to the final result.
For example, we can have expressions to parse decimal numbers into roman numerals.
In the preceding example one class is responsible for interpreting the numbers 1 to 9 while the second handles 10 to 90. So if we combine them we can parse numbers from 1 to 99 as in the following code snippet:
- Expression[] expressions = new Expression[]
- {
- new RomanTenExpression(),
- new RomanOneExpression(),
- };
-
- var context = new RomanContext(99);
-
- foreach (var expression in expressions)
- {
- expression.Interpret(context);
- }
-
- context.Output;
Other practical uses could be parsing source code, or an “engrish sentençe” (did you mean “English sentence”?) and so on.