设计模式——解释器模式(Interpreter Pattern)+ Spring相关源码

文章目录

  • 一、解释器模式定义
  • 二、例子
    • 2.1 菜鸟教程例子
      • 2.1.1 定义一个表达式接口
      • 2.1.2 实现Expression接口
      • 2.1.3 定义解析规则
      • 2.1.4 使用
    • 2.2 JDK源码——Pattern
    • 2.3 Spring源码——ExpressionParser
  • 三、其他设计模式

一、解释器模式定义

类型: 行为型模式
目的: 实现了一个表达式接口,该接口解释一个特定的上下文。这种模式被用在 SQL 解析、符号处理引擎等

二、例子

2.1 菜鸟教程例子

2.1.1 定义一个表达式接口

public interface Expression {
   public boolean interpret(String context);
}

2.1.2 实现Expression接口

public class TerminalExpression implements Expression {
   
   private String data;
 
   public TerminalExpression(String data){
      this.data = data; 
   }
 
   @Override
   public boolean interpret(String context) {
      if(context.contains(data)){
         return true;
      }
      return false;
   }
}
public class OrExpression implements Expression {
    
   private Expression expr1 = null;
   private Expression expr2 = null;
 
   public OrExpression(Expression expr1, Expression expr2) { 
      this.expr1 = expr1;
      this.expr2 = expr2;
   }
 
   @Override
   public boolean interpret(String context) {      
      return expr1.interpret(context) || expr2.interpret(context);
   }
}
public class AndExpression implements Expression {
    
   private Expression expr1 = null;
   private Expression expr2 = null;
 
   public AndExpression(Expression expr1, Expression expr2) { 
      this.expr1 = expr1;
      this.expr2 = expr2;
   }
 
   @Override
   public boolean interpret(String context) {      
      return expr1.interpret(context) && expr2.interpret(context);
   }
}

2.1.3 定义解析规则

public class Expressions {
 
   //规则:Robert 和 John 是男性
   public static Expression getMaleExpression(){
      Expression robert = new TerminalExpression("Robert");
      Expression john = new TerminalExpression("John");
      return new OrExpression(robert, john);    
   }
 
   //规则:Julie 是一个已婚的女性
   public static Expression getMarriedWomanExpression(){
      Expression julie = new TerminalExpression("Julie");
      Expression married = new TerminalExpression("Married");
      return new AndExpression(julie, married);    
   }
}

2.1.4 使用

public class InterpreterPatternDemo {
 
   public static void main(String[] args) {
      Expression isMale = Expressions.getMaleExpression();
      System.out.println("John is male? " + isMale.interpret("John"));
		
      Expression isMarriedWoman = Expressions.getMarriedWomanExpression();
      System.out.println("Julie is a married women? " + isMarriedWoman.interpret("Married Julie"));
   }
}

2.2 JDK源码——Pattern

public final class Pattern implements java.io.Serializable {

	public static Pattern compile(String regex) {
        return new Pattern(regex, 0);
    }
    
	public static Pattern compile(String regex, int flags) {
        return new Pattern(regex, flags);
    }
    
	private String pattern;
	public String pattern() {
        return pattern;
    }
	
	private Pattern(String p, int f) {
        if ((f & ~ALL_FLAGS) != 0) {
            throw new IllegalArgumentException("Unknown flag 0x" + Integer.toHexString(f));
        }
        pattern = p;
        flags = f;

        // to use UNICODE_CASE if UNICODE_CHARACTER_CLASS present
        if ((flags & UNICODE_CHARACTER_CLASS) != 0)
            flags |= UNICODE_CASE;

        // 'flags' for compiling
        flags0 = flags;

        // Reset group index count
        capturingGroupCount = 1;
        localCount = 0;
        localTCNCount = 0;

        if (!pattern.isEmpty()) {
            try {
                compile();
            } catch (StackOverflowError soe) {
                throw error("Stack overflow during pattern compilation");
            }
        } else {
            root = new Start(lastAccept);
            matchRoot = lastAccept;
        }
    }  

	private void compile() {
        .....
    }
}
static class Start extends Node {
    int minLength;
    Start(Node node) {
        this.next = node;
        TreeInfo info = new TreeInfo();
        next.study(info);
        minLength = info.minLength;
    }
    ......
}
static final class StartS extends Start {
     StartS(Node node) {
         super(node);
     }
}
static final class Begin extends Node {
    boolean match(Matcher matcher, int i, CharSequence seq) {
        .......
    }
}
static final class End extends Node {
    boolean match(Matcher matcher, int i, CharSequence seq) {
		...
    }
}

2.3 Spring源码——ExpressionParser

public interface ExpressionParser {
    Expression parseExpression(String expressionString) throws ParseException;

    Expression parseExpression(String expressionString, ParserContext context) throws ParseException;
}

public class SpelExpressionParser extends TemplateAwareExpressionParser {
    private final SpelParserConfiguration configuration;

    public SpelExpressionParser() {
        this.configuration = new SpelParserConfiguration();
    }

    public SpelExpressionParser(SpelParserConfiguration configuration) {
        Assert.notNull(configuration, "SpelParserConfiguration must not be null");
        this.configuration = configuration;
    }

    public SpelExpression parseRaw(String expressionString) throws ParseException {
        Assert.hasText(expressionString, "'expressionString' must not be null or blank");
        return this.doParseExpression(expressionString, (ParserContext)null);
    }

    protected SpelExpression doParseExpression(String expressionString, @Nullable ParserContext context) throws ParseException {
        return (new InternalSpelExpressionParser(this.configuration)).doParseExpression(expressionString, context);
    }
}

class InternalSpelExpressionParser extends TemplateAwareExpressionParser {

	private final Deque<SpelNodeImpl> constructedNodes = new ArrayDeque();
	
	protected SpelExpression doParseExpression(String expressionString, @Nullable ParserContext context) throws ParseException {
        this.checkExpressionLength(expressionString);

        try {
            this.expressionString = expressionString;
            Tokenizer tokenizer = new Tokenizer(expressionString);
            this.tokenStream = tokenizer.process();
            this.tokenStreamLength = this.tokenStream.size();
            this.tokenStreamPointer = 0;
            this.constructedNodes.clear();
            SpelNodeImpl ast = this.eatExpression();
            if (ast == null) {
                throw new SpelParseException(this.expressionString, 0, SpelMessage.OOD, new Object[0]);
            } else {
                Token t = this.peekToken();
                if (t != null) {
                    throw new SpelParseException(this.expressionString, t.startPos, SpelMessage.MORE_INPUT, new Object[]{this.toString(this.nextToken())});
                } else {
                    return new SpelExpression(expressionString, ast, this.configuration);
                }
            }
        } catch (InternalParseException var6) {
            throw var6.getCause();
        }
    }


}

三、其他设计模式

创建型模式
结构型模式

  • 1、设计模式——装饰器模式(Decorator Pattern)+ Spring相关源码

行为型模式

  • 1、设计模式——访问者模式(Visitor Pattern)+ Spring相关源码
  • 2、设计模式——中介者模式(Mediator Pattern)+ JDK相关源码
  • 3、设计模式——策略模式(Strategy Pattern)+ Spring相关源码
  • 4、设计模式——状态模式(State Pattern)
  • 5、设计模式——命令模式(Command Pattern)+ Spring相关源码
  • 6、设计模式——观察者模式(Observer Pattern)+ Spring相关源码
  • 7、设计模式——备忘录模式(Memento Pattern)
  • 8、设计模式——模板方法模式(Template Pattern)+ Spring相关源码
  • 9、设计模式——迭代器模式(Iterator Pattern)+ Spring相关源码
  • 10、设计模式——责任链模式(Chain of Responsibility Pattern)+ Spring相关源码
  • 11、设计模式——解释器模式(Interpreter Pattern)+ Spring相关源码

你可能感兴趣的:(Programming,Concepts,设计模式,解释器模式,spring,interpreter,pattern)