Design Pattern interpreter parser Mode

Source: Internet
Author: User

The parser itself is a large design model, with the focus on designing the parser itself. However, because the parser itself is difficult to design, the perfect parser mode is rarely used, however, the idea of this design pattern is not difficult.

The following is a simple and practical method for C ++ to implement the parser mode. If different Resolvers are used, different results will be parsed for the same content.


# Include <stdio. h ># include <string> using namespace STD; Class context {public: String cmd; void setcontext (string s) {cmd = s ;}}; class interpreterbase {protected: context * context; public: interpreterbase (Context * C): Context (c) {}// virtual void interpret () will not be able to parse External commands if it is not written = 0 (); virtual void interpret () = 0 ;}; class interpreterincre: Public interpreterbase {public: interpreterincre( context * C): interpreterbase (c) {} void interpret () {string cmd = context-> cmd; For (INT I = 0; I <(INT) cmd. size (); I ++) {putchar (CMD [I] + 1);} putchar ('\ n') ;}}; class interpreterdere: Public interpreterbase {public: interpreterdere (Context * C): interpreterbase (c) {} void interpret () {string cmd = context-> cmd; For (INT I = 0; I <(INT) cmd. size (); I ++) {putchar (CMD [I]-1) ;}putchar ('\ n') ;}; int main () {context; context. setcontext ("abcdefg"); interpreterdecredere (& context); interpreterincreinre (& context); Decret. interpret (); incret. interpret (); Return 0 ;}

The running result returns different results for the same string abcdefg using different Resolvers:



It can be said that the C \ c ++ compiler is written using this design mode. It is of course difficult to improve the implementation of such a parser.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.