Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1736408
  • 博文数量: 438
  • 博客积分: 9799
  • 博客等级: 中将
  • 技术积分: 6092
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-25 17:25
文章分类

全部博文(438)

文章存档

2019年(1)

2013年(8)

2012年(429)

分类: C/C++

2012-03-25 19:42:33

这种模式一般用来为一门语言创建解释器。解释语言时,会从一段上下文(context)开始解析。而这个上下文会由不同的部分组成,各个部分有不同的解析方式。比如一段html
  1. <html>
  2.   <head>
  3.   </head>
  4.   <body>
  5.   </body>
  6. </html>

解析器的类层次结构可以是:
  1. interface Expression { virtual void interpret(string context) = 0; }

  2. class HtmlExpression : public Expression
  3. {
  4.     virtual void interpret(string context)
  5.     {
  6.         parseHtml(context);

  7.         string headContext = getHeadContext(context);
  8.         Expression* pHeadExp = new HeadExpression;
  9.         pHeadExp->interpret(headContext);

  10.         string bodyContext = getBodyContext(context);
  11.         Expression* pBodyExp = new BodyExpression;
  12.         pBodyExp->interpret(bodyContext);
  13.     }
  14. };

  15. class HeadExpression : public Expression
  16. {
  17.     virtual void interpret(string context)
  18.     {
  19.         parseHead(context);
  20.     }
  21. };

  22. class BodyExpression : public Expression
  23. {
  24.     virtual void interpret(string context)
  25.     {
  26.         parseBody(context);
  27.     }
  28. };

阅读(1365) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~