《设计模式系列》 ---解释器模式

本文深入探讨了解释器模式的基本概念,并通过Java代码实例展示了如何实现这一模式。解释器模式提供了一种将表达式表示为树结构的方法,允许在不修改原有代码的情况下解析这些表达式。

 解释器模式:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。

/**
 * @author stefanie zhao
 * @date 2014-8-21 下午04:37:29
 */
public class Context {

    private String input;
    private String output;

    /**
     * @return the input
     */
    public String getInput() {
        return input;
    }

    /**
     * @param input
     *            the input to set
     */
    public void setInput(String input) {
        this.input = input;
    }

    /**
     * @return the output
     */
    public String getOutput() {
        return output;
    }

    /**
     * @param output
     *            the output to set
     */
    public void setOutput(String output) {
        this.output = output;
    }

}
/**
 * @author stefanie zhao
 * @date 2014-8-21 下午04:37:03
 */
public abstract class AbstractExpression {

    public abstract void interpret(Context context);
}
/**
 * @author stefanie zhao
 * @date 2014-8-21 下午04:38:16
 */
public class NonterminalExpression extends AbstractExpression {

    public void interpret(Context context) {
        // TODO Auto-generated method stub
        System.out.println("非终端解释器");
    }

}
/**
 * @author stefanie zhao
 * @date 2014-8-21 下午04:38:16
 */
public class TerminalExpression extends AbstractExpression {

    public void interpret(Context context) {
        // TODO Auto-generated method stub
        System.out.println("终端解释器");
    }

}
public class Main {

    /**
     * @Description: TODO
     * @param @param args
     * @return void
     * @throws
     */
    public static void main(String[] args) {
        Context context = new Context();
        List<AbstractExpression> list = new ArrayList<AbstractExpression>();
        list.add(new TerminalExpression());
        list.add(new NonterminalExpression());
        list.add(new TerminalExpression());
        list.add(new TerminalExpression());

        for (AbstractExpression a : list)
            a.interpret(context);
    }

}


转载于:https://my.oschina.net/stefanzhlg/blog/308130

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值