2. Introduction
Given a language, define a
representation for its grammar along
with an interpreter that uses the
representation to interpret sentences
in the language. (GOF) ***
***The basic idea is to have a class for each
symbol(terminal or nonterminal) in a specialized computer
language.
4. ● Sentences in the language
represented as abstract syntax
trees (AST)
● Easy to extend and modify
grammar. (Classes
implementation that describes
abstract syntax nodes easily
coded)
● You can easily change the
method of calculating
expressions
Problem solving
15. View - slide 2
render(priceContext) {
let output = this.template,
vars = this.getVars();
vars.forEach((variable)=> {
let expName = variable.toLowerCase(),
re = new RegExp("{" + variable + "}", 'g');
output = output.replace(re, priceContext.interpret(expName));
});
this.el.innerHTML = output;
return this;
}
}
16. Usage
const Main = () => {
let el = document.body;
let view = new View(el, 'contextTpl');
let smallPackage = new SPackage();
smallPackage.add(new TV());
smallPackage.add(new LapTop());
let bigPackage = new BPackage();
bigPackage.add(new Table());
bigPackage.add(new Bed());
bigPackage.add(new Bed());
bigPackage.add(new TV());
let priceContext = new PriceContext(
new Bed(),
new Table(),
new TV(),
new LapTop(),
smallPackage,
bigPackage
);
priceContext.setPrice({
'Bed': 400,
'TV': 200,
'LapTop': 500,
'Table': 50
});
view.render(priceContext);
};
18. Advantages Disadvantages
● You have a simple
language to interpret
● You can easily change
the method of
calculating expressions
● You can represent
sentences in the
language as abstract
syntax trees (AST).
● Difficult to support the
grammar with a large
number of rules
● Each class on each
expression
19. Related Patterns
● Composite for same proccessing terminal and non-terminal expressions
● Flyweight for sharing terminal expressions
● Iterator for traversing the nodes of non-terminals