看看用TypeScript怎样实现常见的设计模式,顺便复习一下。

学模式最重要的不是记UML,而是知道什么模式可以解决什么样的问题,在做项目时碰到问题可以想到用哪个模式可以解决,UML忘了可以查,思想记住就好。

这里尽量用原创的,实际中能碰到的例子来说明模式的特点和用处。

解释器模式 Interpreter

特点:使用给定语法来解释一段内容。

用处:管理类系统经常会定义一些搜索语句格式来使用户方便搜索库里的内容,这时就可以考虑用解释器来翻译执行这些语句。

注意:适合相对简单的语法。

解释器模式通过把一段表达式拆开成很多个,分为不同的解析类,一个一个的去解析并执行,这过程中经常会用Context来保存解析过程的信息。

这种解释器的优点在于各种表达式的解析相对独立,要加入新的规则也不会影响现有的解析。缺点也很明显,一个表达式一个类,复杂语法或复合语法的话表达式数量就非常多,并且表达式之间也很难真正独立。

下面用TypeScript写一个简单正则表达式的解释器:

要解释的表达式有:{}, [], \d, ^, $这几种。

先建立一个Expression接口,所有解释器都实现这个接口:

interface Expression{
interpret(context: Context);
}

可以看到接口里用到了一个Context,这个用来保存解析时的一些数据和进度,包含:

pattern: 整个表达式

currentPatternIndex: 当前正在验证的表达式的位置

lastExpression: 上一个表达式,用于{}解析

text: 需要验证的文本

currentTextIndex: 当前验证到text里的哪个字符的位置

isMatch: 是否匹配成功

class Context{
constructor(public pattern: string, public text: string){ } currentTextIndex: number = 0;
get currentText(): string{
return this.text[this.currentTextIndex];
} currentPatternIndex: number = 0;
lastExpression: string;
get currentPatternExpression(): string{
return this.pattern[this.currentPatternIndex];
} isMatch: boolean;
}

现在分别给那些符号写解析类:

// 开始符号:^
class BeginExpression implements Expression{
interpret(context: Context){
context.isMatch = context.currentPatternIndex === 0;
context.currentPatternIndex++;
}
} // 结束符号:$
class EndExpression implements Expression{
interpret(context: Context){
context.isMatch = context.currentTextIndex === context.text.length;
context.currentPatternIndex++;
}
} // 反斜杠:\d,只支持\d
class BslashExpression implements Expression{
interpret(context: Context){
if(context.pattern[context.currentPatternIndex + 1] !== 'd'){
throw new Error('only support \\d');
} let target = context.currentText;
context.lastExpression = '\\d';
context.isMatch = Number.isInteger(Number.parseInt(target));
context.currentPatternIndex+=2;
context.currentTextIndex++;
}
} // 中括号:[]
class BracketExpression implements Expression{
interpret(context: Context){
let prevIndex = context.currentPatternIndex;
while(context.pattern[++context.currentPatternIndex] !== ']'){
if(context.currentPatternIndex+1 === context.pattern.length){
throw new Error(`miss symbol ]`);
}
}
let expression = context.pattern.substr(prevIndex+1, context.currentPatternIndex - prevIndex - 1);
let target = context.currentText; context.lastExpression = `[${expression}]`;
context.isMatch = [...expression].indexOf(target) > -1;
context.currentPatternIndex++;
context.currentTextIndex++;
}
} // 大括号:{}
class BraceExpression implements Expression{
interpret(context: Context){
let endIndex = context.currentPatternIndex;
while(context.pattern[++endIndex] !== '}'){
if(i+1 === context.pattern.length){
throw new Error(`miss symbol }`);
}
}
let expression = context.pattern.substr(context.currentPatternIndex + 1, endIndex - context.currentPatternIndex - 1);
let num = Number.parseInt(expression);
if(!Number.isInteger(num)){
throw new Error('{} only support number');
}
let newExpression = '';
for(let i=1;i<num;i++){
newExpression += context.lastExpression;
}
context.pattern = context.pattern.substr(0, context.currentPatternIndex) +
newExpression +
context.pattern.substr(endIndex+1);
}
} // 普通字符
class StringExpression implements Expression{
interpret(context: Context){
context.lastExpression = context.currentPatternExpression;
context.isMatch = context.currentPatternExpression === context.currentText;
context.currentPatternIndex++;
context.currentTextIndex++;
}
}

有了这些解释器,现在解析表达式就很轻松了:

class Regex{
mapping: {[key:string]: Expression} = {
'^': new BeginExpression(),
'$': new EndExpression(),
'{': new BraceExpression(),
'[': new BracketExpression(),
'\\':new BslashExpression(),
}; // 这是一个表达式-解释器的映射表
stringExp: Expression = new StringExpression(); constructor(private pattern: string){ } IsMatch(text: string): boolean{
let context = new Context(this.pattern, text); for(context.currentPatternIndex=0;context.currentPatternIndex<context.pattern.length;){
let symbol = this.mapping[context.currentPatternExpression];
symbol ? symbol.interpret(context) : this.stringExp.interpret(context); //通过找到对应的解释器来解释匹配文本
if(!context.isMatch){
break;
}
}
return context.isMatch;
}
}

写个手机号码验证的正则表达式测试一下:

let pattern = '/^1[34578]\d{9}$/';
let regex = new Regex(pattern); let text = '13712345678';
console.log(`match ${text}: ${regex.IsMatch(text)}`); // 正常手机号:成功 text = '1371234567p';
console.log(`match ${text}: ${regex.IsMatch(text)}`); // 手机号里有字母:失败 text = '137123456789';
console.log(`match ${text}: ${regex.IsMatch(text)}`); // 多了一位:失败 text = '1371234567';
console.log(`match ${text}: ${regex.IsMatch(text)}`); // 少了一位:失败

结果符合预期,可以看到用解释器把表达分开解释的好处很明显,各个解释器互不干扰,主体部分调用这些解释器分别进行解释就可以了,非常方便。

当然这也只是处理简单的语法,如果语法很复杂就需要考虑引入分析引擎或编译器了。

TypeScript设计模式之解释器的更多相关文章

  1. 乐在其中设计模式(C#) - 解释器模式(Interpreter Pattern)

    原文:乐在其中设计模式(C#) - 解释器模式(Interpreter Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 解释器模式(Interpreter Pattern) 作 ...

  2. 设计模式:解释器(Interpreter)模式

    设计模式:解释器(Interpreter)模式 一.前言 这是我们23个设计模式中最后一个设计模式了,大家或许也没想到吧,竟然是编译原理上的编译器,这样说可能不对,因为编译器分为几个部分组成呢,比如词 ...

  3. C#设计模式:解释器模式(Interpreter Pattern)

    一,C#设计模式:解释器模式(Interpreter Pattern) 1,解释器模式的应用场合是Interpreter模式应用中的难点,只有满足“业务规则频繁变化,且类似的模式不断重复出现,并且容易 ...

  4. 北风设计模式课程---解释器模式(Interpreter Pattern)

    北风设计模式课程---解释器模式(Interpreter Pattern) 一.总结 一句话总结: 不仅要通过视频学,还要看别的博客里面的介绍,搜讲解,搜作用,搜实例 设计模式都是对生活的抽象,比如用 ...

  5. python设计模式之解释器模式

    python设计模式之解释器模式 对每个应用来说,至少有以下两种不同的用户分类. [ ] 基本用户:这类用户只希望能够凭直觉使用应用.他们不喜欢花太多时间配置或学习应用的内部.对他们来说,基本的用法就 ...

  6. 【GOF23设计模式】解释器模式 & 访问者模式

    来源:http://www.bjsxt.com/ 一.[GOF23设计模式]_解释器模式.访问者模式.数学表达式动态解析库式 1.解释器模式Interpreter  2.访问者模式Visitor 

  7. [设计模式] 15 解释器模式 Interpreter

    在GOF的<设计模式:可复用面向对象软件的基础>一书中对解释器模式是这样说的:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子.如果一种特定类 ...

  8. TypeScript设计模式之单例、建造者、原型

    看看用TypeScript怎样实现常见的设计模式,顺便复习一下. 单例模式 Singleton 特点:在程序的生命周期内只有一个全局的实例,并且不能再new出新的实例. 用处:在一些只需要一个对象存在 ...

  9. TypeScript设计模式之工厂

    看看用TypeScript怎样实现常见的设计模式,顺便复习一下. 学模式最重要的不是记UML,而是知道什么模式可以解决什么样的问题,在做项目时碰到问题可以想到用哪个模式可以解决,UML忘了可以查,思想 ...

随机推荐

  1. HttpServletRequest和ServletRequest的区别

    servlet理论上可以处理多种形式的请求响应形式,http只是其中之一所以HttpServletRequest HttpServletResponse分别是ServletRequest和Servle ...

  2. Bootstrap入门(十八)组件12:徽章与巨幕

    Bootstrap入门(十八)组件12:徽章与巨幕 1.徽章 2.巨幕 1.徽章 给链接.导航等元素嵌套 <span class="badge"> 元素,可以很醒目的展 ...

  3. CodeForces 722A

    A. Broken Clock time limit per test:1 second memory limit per test:256 megabytes input:standard inpu ...

  4. .Net程序员学用Oracle系列(11):系统函数(下)

    1.聚合函数 1.1.COUNT 函数 1.2.SUM 函数 1.3.MAX 函数 1.4.MIN 函数 1.5.AVG 函数 2.ROWNUM 函数 2.1.ROWNUM 函数简介 2.2.利用 R ...

  5. Got minus one from a read call异常

    Caught: java.sql.SQLException: Io 异常: Got minus one from a read call使用JDBC连接Oracle时,多次出现上述错误,后来去网上找了 ...

  6. String,StringBuffer,StringBuilder个人认为较重要的区别

        今天在整理不可变对象知识点时,突然看到了String,StringBuffer,StringBuilder三者的区别,这里就挑一些我认为比较重要的点记录一下,方便日后查看.     Strin ...

  7. synchronized的使用及注意事项

    主要来源:http://blog.csdn.net/luoweifu/article/details/46613015 1.synchronized(this) void method(){ sync ...

  8. OSS.Common获取枚举字典列表标准库支持

    上篇(.Net Standard扩展支持实例分享)介绍了OSS.Common的标准库支持扩展,也列举了可能遇到问题的解决方案.由于时间有限,同时.net standard暂时还没有提供对Descrip ...

  9. mybatis随笔三之SqlSession

    在上一篇文章我们已经得到了DefaultSqlSession,接下来我们对sqlSession.getMapper(DemoMapper.class)这种语句进行分析 @Override public ...

  10. 基于vue2+vuex2+vue-router+axios+elementUI做的自动化后台模板

    github地址:https://github.com/sailengsi/sls-admin 此项目重点突出在架构上模式,这个架构模式,可以让我们在开发中,很方便的拓展与维护,并且可以保持结构清晰的 ...