Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Interpreter pattern

From Wikipedia, the free encyclopedia
Approach in computer programming
icon
This articleneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "Interpreter pattern" – news ·newspapers ·books ·scholar ·JSTOR
(November 2008) (Learn how and when to remove this message)

Incomputer programming, theinterpreter pattern is adesign pattern that specifies how to evaluate sentences in a language.The basic idea is to have aclass for each symbol (terminal ornonterminal) in aspecialized computer language. Thesyntax tree of a sentence in the language is an instance of thecomposite pattern and is used to evaluate (interpret) the sentence for a client.[1]: 243  See alsoComposite pattern.

Overview

[edit]

The Interpreter[2]design pattern is one of the twenty-three well-knownGoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.

What problems can the Interpreter design pattern solve?

[edit]

Source:[3]

  • Agrammar for a simple language should be defined
  • so that sentences in the language can be interpreted.

When a problem occurs very often, it could be considered to represent it as a sentence in a simple language(Domain Specific Languages) so that an interpreter can solve the problemby interpreting the sentence.

For example, when many different or complex search expressions must be specified.Implementing (hard-wiring) them directly into a class is inflexiblebecause it commits the class to particular expressions and makes it impossible to specify new expressions or change existing ones independently from (without having to change) the class.

What solution does the Interpreter design pattern describe?

[edit]
  • Define a grammar for a simple language by defining anExpression class hierarchy and implementing aninterpret() operation.
  • Represent a sentence in the language by an abstract syntax tree (AST) made up ofExpression instances.
  • Interpret a sentence by callinginterpret() on the AST.

The expression objects are composed recursively into a composite/tree structure that is calledabstract syntax tree (seeComposite pattern).
The Interpreter pattern doesn't describe howto build an abstract syntax tree. This canbe done either manually by a client or automatically by aparser.

See also the UML class and object diagram below.

Uses

[edit]
  • Specialized database query languages such asSQL.
  • Specialized computer languages that are often used to describe communication protocols.
  • Most general-purpose computer languages actually incorporate several specialized languages[citation needed].

Structure

[edit]

UML class and object diagram

[edit]
A sample UML class and object diagram for the Interpreter design pattern.[4]

In the aboveUMLclass diagram, theClient class refers to the commonAbstractExpression interface for interpreting an expressioninterpret(context).
TheTerminalExpression class has no children and interprets an expression directly.
TheNonTerminalExpression class maintains a container of child expressions(expressions) and forwards interpret requeststo theseexpressions.

The object collaboration diagram shows the run-time interactions: TheClient object sends an interpret request to the abstract syntax tree.The request is forwarded to (performed on) all objects downwards the tree structure.
TheNonTerminalExpression objects (ntExpr1,ntExpr2) forward the request to their child expressions.
TheTerminalExpression objects (tExpr1,tExpr2,…) perform the interpretation directly.

UML class diagram

[edit]

Example

[edit]

This C++23 implementation is based on the pre C++98 sample code in the book.

importstd;usingString=std::string;template<typenameK,typenameV>usingTreeMap=std::map<K,V>;template<typenameT>usingUniquePtr=std::unique_ptr<T>;classBooleanExpression{public:BooleanExpression()=default;virtual~BooleanExpression()=default;virtualboolevaluate(Context&)=0;virtualUniquePtr<BooleanExpression>replace(String&,BooleanExpression&)=0;virtualUniquePtr<BooleanExpression>copy()const=0;};classVariableExpression;classContext{private:TreeMap<constVariableExpression*,bool>m;public:Context()=default;[[nodiscard]]boollookup(constVariableExpression*key)const{returnm.at(key);}voidassign(VariableExpression*key,boolvalue){m[key]=value;}};classVariableExpression:publicBooleanExpression{private:Stringname;public:VariableExpression(constString&name):name{name}{}virtual~VariableExpression()=default;[[nodiscard]]virtualboolevaluate(Context&context)const{returncontext.lookup(this);}[[nodiscard]]virtualUniquePtr<VariableExpression>replace(constString&name,BooleanExpression&exp){if(this->name==name){returnstd::make_unique<VariableExpression>(exp.copy());}else{returnstd::make_unique<VariableExpression>(name);}}[[nodiscard]]virtualUniquePtr<BooleanExpression>copy()const{returnstd::make_unique<BooleanExpression>(name);}VariableExpression(constVariableExpression&)=delete;VariableExpression&operator=(constVariableExpression&)=delete;};classAndExpression:publicBooleanExpression{private:UniquePtr<BooleanExpression>operand1;UniquePtr<BooleanExpression>operand2;public:AndExpression(UniquePtr<BooleanExpression>op1,UniquePtr<BooleanExpression>op2):operand1{std::move(op1)},operand{std::move(op2)}{}virtual~AndExpression()=default;[[nodiscard]]virtualboolevaluate(Context&context)const{returnoperand1->evaluate(context)&&operand2->evaluate(context);}[[nodiscard]]virtualUniquePtr<BooleanExpression>replace(constString&name,BooleanExpression&exp)const{returnstd::make_unique<AndExpression>(operand1->replace(name,exp),operand2->replace(name,exp));}[[nodiscard]]virtualUniquePtr<BooleanExpression>copy()const{returnstd::make_unique<AndExpression>(operand1->copy(),operand2->copy());}AndExpression(constAndExpression&)=delete;AndExpression&operator=(constAndExpression&)=delete;};intmain(intargc,char*argv[]){UniquePtr<BooleanExpression>expression;Contextcontext;UniquePtr<VariableExpression>x=std::make_unique<VariableExpression>("X");UniquePtr<VariableExpression>y=std::make_unique<VariableExpression>("Y");UniquePtr<BooleanExpression>expression;=std::make_unique<AndExpression>(x,y);context.assign(x.get(),false);context.assign(y.get(),true);boolresult=expression->evaluate(context);std::println("{}",result);context.assign(x.get(),true);context.assign(y.get(),true);result=expression->evaluate(context);std::println("{}",result);return0;}

The program output is:

01

See also

[edit]

References

[edit]
  1. ^Gamma, Erich;Helm, Richard; Johnson, Ralph; Vlissides, John (1994).Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley.ISBN 0-201-63361-2.
  2. ^Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994).Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 243ff.ISBN 0-201-63361-2.{{cite book}}: CS1 maint: multiple names: authors list (link)
  3. ^"The Interpreter design pattern - Problem, Solution, and Applicability".w3sDesign.com. Retrieved2017-08-12.
  4. ^"The Interpreter design pattern - Structure and Collaboration".w3sDesign.com. Retrieved2017-08-12.

External links

[edit]
The WikibookComputer Science Design Patterns has a page on the topic of:Interpreter
Gang of Four
patterns
Creational
Structural
Behavioral
Concurrency
patterns
Architectural
patterns
Other
patterns
Books
People
Communities
See also
Retrieved from "https://en.wikipedia.org/w/index.php?title=Interpreter_pattern&oldid=1324173364"
Category:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp