解释器模式:提供了评估语言的语法或表达式的方式,它属于行为型模式。这种模式实现了一个表达式接口,该接口解释一个特定的上下文。
主要意图:给定一个语言,定义它的文法表示,并定义一个解释器,这个解释器使用该标识来解释语言中的句子。
主要解决:对于一些固定文法构建一个解释句子的解释器。
解决方案:构建语法树,定义终结符与非终结符。
优点:
1、可扩展性比较好,灵活。
2、增加了新的解释表达式的方式。
3、易于实现简单文法。
缺点:
1、可利用场景比较少。
2、对于复杂的文法比较难维护。
3、解释器模式会引起类膨胀。
4、解释器模式采用递归调用方法。
解释器类图:
代码实现:
客户端代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25using System; using System.Collections.Generic; namespace _01解释器模式_结构图 { class Program { static void Main(string[] args) { Context context = new Context(); IList<AbstractExpression> list = new List<AbstractExpression>(); list.Add(new TerminalExpression()); list.Add(new NonterminalExpression()); list.Add(new TerminalExpression()); list.Add(new TerminalExpression()); foreach (AbstractExpression exp in list) { exp.Interpret(context); } Console.Read(); } } }
抽象解释器:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12using System; using System.Collections.Generic; using System.Text; namespace _01解释器模式_结构图 { abstract class AbstractExpression { public abstract void Interpret(Context context); } }
终结符表达式:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15using System; using System.Collections.Generic; using System.Text; namespace _01解释器模式_结构图 { class TerminalExpression:AbstractExpression { public override void Interpret(Context context) { Console.WriteLine("终端解释器"); } } }
非终结符表达式:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15using System; using System.Collections.Generic; using System.Text; namespace _01解释器模式_结构图 { class NonterminalExpression:AbstractExpression { public override void Interpret(Context context) { Console.WriteLine("非终端解释器"); } } }
环境角色:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23using System; using System.Collections.Generic; using System.Text; namespace _01解释器模式_结构图 { class Context { private string input; public string Input { get { return input; } set { input = value; } } private string output; public string Output { get { return output; } set { output = value; } } } }
最后
以上就是顺利香烟最近收集整理的关于设计模式之解释器模式的全部内容,更多相关设计模式之解释器模式内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复