解释器模式(interpreter):给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
解释器模式Demo:
/**
* 2018年4月10日下午9:01:06
*/
package com.Designpattern;
/**
* @author xinwenfeng
*
*/
public class TestInterpreter {
/**
* @param args
*/
public static void main(String[] args) {
// 01 02 03 04 05 06 07 08 09 10
// a b c d e f g h i j
// 11 12 13 14 15 16 17 18 19 20
// k l m n o p q r s t
// 21 22 23 24 25 26
// u v w x y z
WordContext context = new WordContext();
context.setText("U23L15U24L09U08L21L01L14U14L09");
WordExpression expression = null;
UpperWordExpression u = new UpperWordExpression();
LowerWordExpression l = new LowerWordExpression();
while(context.getText().length()>0) {
if("U".equals(context.getText().substring(0, 1))) {
expression = u;
}else {
expression = l;
}
expression.interpret(context);
}
}
}
class WordContext{
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
//解释器
abstract class WordExpression{
public abstract void interpret(WordContext context);
}
class UpperWordExpression extends WordExpression{
@Override
public void interpret(WordContext context) {
String word = context.getText().substring(1,3);//可放父类复用
int num = Integer.parseInt(word);
char returnWord = (char) ('a'+(num -1));
context.setText(context.getText().substring(3));
System.out.print((" "+returnWord).toUpperCase());
}
}
class LowerWordExpression extends WordExpression{
@Override
public void interpret(WordContext context) {
String word = context.getText().substring(1,3);
int num = Integer.parseInt(word);
char returnWord = (char) ('a'+(num -1));
context.setText(context.getText().substring(3));
System.out.print(returnWord);
}
}
结果: