zoukankan      html  css  js  c++  java
  • JavaScript设计模式样例二十一 —— 解释器模式

    解释器模式(Interpreter Pattern)

    定义:提供了评估语言的语法或表达式的方式。
    目的:对于一些固定文法构建一个解释句子的解释器。
    场景:编译器、运算表达式计算。
    // 定义对于语法的断言
    class TerminalExpression {
        constructor (data) {
            this.data = data
        }
    
        interpret (context) {
            if (context.indexOf(this.data) > -1) {
                return true
            }
            return false
        }
    }
    
    // 添加表达式判断符
    class OrExpression {
        constructor(expr1, expr2) {
            this.expr1 = expr1;
            this.expr2 = expr2;
        }
        interpret(context) {
            return this.expr1.interpret(context) || this.expr2.interpret(context);
        }
    }
    class AndExpression {
        constructor(expr1, expr2) {
            this.expr1 = expr1;
            this.expr2 = expr2;
        }
        interpret(context) {
            return this.expr1.interpret(context) && this.expr2.interpret(context);
        }
    }
    
    
    // 获取对应表达式
    function getMaleExpression(){
        const robert = new TerminalExpression("Robert");
        const john = new TerminalExpression("John");
        return new OrExpression(robert, john);
    }
    function getMarriedWomanExpression(){
        const julie = new TerminalExpression("Julie");
        const married = new TerminalExpression("Married");
        return new AndExpression(julie, married);
    }
    
    
    // 判断语句断言
    const isMale = getMaleExpression();
    const isMarriedWoman = getMarriedWomanExpression();
    console.log("John is male? " + isMale.interpret("John"));
    console.log("Julie is a married women? " )

    Git地址:https://github.com/skillnull/Design-Mode-Example

  • 相关阅读:
    中文词频统计及词云制作 25
    实验一 DOS实验 25
    字符串练习 25
    Python、循环的练习 25
    用requests库和BeautifulSoup4库爬取新闻列表 25
    爬取新闻列表 25
    Mockito使用总结
    20121116
    20121123
    20121115
  • 原文地址:https://www.cnblogs.com/Man-Dream-Necessary/p/12704969.html
Copyright © 2011-2022 走看看