解析器模式

      解释器模式(Interpreter):给定一个语言,定义它的文法的一种表示。解析器主要分为终结符表达式和非终结符表达式:A=B+CBC是终结符;+号是非终结符。

类图:

代码:

publicclass Context {

    private Object context;

    public Object getContext() {

       returncontext;

    }

    publicvoid setContext(Object context) {

       this.context = context;

    }

}

publicinterface Expression {

    publicvoid interpret(Context context);

}

publicclass TerminalExpression implements Expression {

    @Override

    publicvoid interpret(Context context) {

       System.out.println("终端符表达式处理内容:"+context.getContext());

    }

}

publicclass NonterminalExpression implements Expression {

    @Override

    publicvoid interpret(Context context) {

       System.out.println("非终端符表达式处理内容:"+context.getContext());

    }

}

publicstaticvoid main(String[] args) {

       Context context=new Context();

       context.setContext("speaking");

       Expression e1=new TerminalExpression();

       Expression e2=new NonterminalExpression();

       //同样的内容用不同的解析器解析得到不一样的结果。

       e1.interpret(context);

       e2.interpret(context);

    }

优点:扩展性强,修改语法只需修改对应的解析器类就可以。

缺点:当语法非常复杂的时候就会有难以管理。这时可以使用其他技术解决(语法分析程序)

    当一个语言需要解析执行,并且你可将该语言中的句子表示为一个抽象语法树,可使用解析器模式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值