(设计模式)解释器
Posted 多元思维的开发者
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(设计模式)解释器相关的知识,希望对你有一定的参考价值。
解释器模式:
ps:图片来自《大话设计模式》
例子:
/**
* Copies regular expression to an int array and invokes the parsing
* of the expression which will create the object tree.
* 编译正则表达式,形式一个抽象语法树
*/
private void compile() {
// Handle canonical equivalences
// 处理单纯的值比较
if (has(CANON_EQ) && !has(LITERAL)) {
// 将正则模式化
normalize();
} else {
normalizedPattern = pattern;
}
patternLength = normalizedPattern.length();
// Copy pattern to int array for convenience
// Use double zero to terminate pattern
temp = new int[patternLength + 2];
hasSupplementary = false;
int c, count = 0;
// Convert all chars into code points
for (int x = 0; x < patternLength; x += Character.charCount(c)) {
c = normalizedPattern.codePointAt(x);
if (isSupplementary(c)) {
hasSupplementary = true;
}
temp[count++] = c;
}
patternLength = count; // patternLength now in code points
if (! has(LITERAL))
RemoveQEQuoting();
// Allocate all temporary objects here.
buffer = new int[32];
groupNodes = new GroupHead[10];
namedGroups = null;
// 处理有文字
if (has(LITERAL)) {
// Literal pattern handling
matchRoot = newSlice(temp, patternLength, hasSupplementary);
matchRoot.next = lastAccept;
} else {
// 递归解析,这里expr就是解释的入口
matchRoot = expr(lastAccept);
// Check extra pattern characters
if (patternLength != cursor) {
if (peek() == ')') {
throw error("Unmatched closing ')'");
} else {
throw error("Unexpected internal error");
}
}
}
// Peephole optimization
if (matchRoot instanceof Slice) {
root = BnM.optimize(matchRoot);
if (root == matchRoot) {
root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot);
}
} else if (matchRoot instanceof Begin || matchRoot instanceof First) {
root = matchRoot;
} else {
root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot);
}
// Release temporary storage
temp = null;
buffer = null;
groupNodes = null;
patternLength = 0;
compiled = true;
}
模式分析:
以上是关于(设计模式)解释器的主要内容,如果未能解决你的问题,请参考以下文章