设计模式---解释器模式

 

/*
 * 上下文环境类,用来保存文法
 */
public class Context {
	
	private String input;
	private int output;
	
	public Context(String input) {
		this.input = input;
	}
	
	public String getInput() {
		return input;
	}
	public void setInput(String input) {
		this.input = input;
	}
	public int getOutput() {
		return output;
	}
	public void setOutput(int output) {
		this.output = output;
	}
}

 

/*
 * 抽象解释器
 */
public abstract class Expression {
	
	public abstract void interpret(Context context);
	
}

 


public class MinusExpression extends Expression {

	public void interpret(Context context) {
		System.out.println("自动递减");
		String input = context.getInput();
		int inInput = Integer.parseInt(input);
//		inInput--;
		--inInput;
		context.setInput(String.valueOf(inInput));
		context.setOutput(inInput);
	}

}

 


public class PlusExpression extends Expression {

	public void interpret(Context context) {
		//提示信息
		System.out.println("自动递增");
		//获得上下文环境
		String input = context.getInput();
		//进行类型转换
		int intInput = Integer.parseInt(input);
		//进行递增
//		intInput++;
		++intInput;
		//对上下文环境重新进行赋值
		context.setInput(String.valueOf(intInput));
		context.setOutput(intInput);
	}

}
import java.util.ArrayList;
import java.util.List;

/*
 * client
 */
public class MainClass {
	public static void main(String[] args) {
		String number = "20";
		Context context = new Context(number);
		
//		Expression expression1 = new MinusExpression();
//		expression1.interpret(context);
//		System.out.println(context.getOutput());
//		
//		Expression expression2 = new PlusExpression();
//		expression2.interpret(context);
//		System.out.println(context.getOutput());
//		
//		Expression expression3 = new PlusExpression();
//		expression3.interpret(context);
//		System.out.println(context.getOutput());
//		
//		Expression expression4 = new PlusExpression();
//		expression4.interpret(context);
//		System.out.println(context.getOutput());
		
		List<Expression> list = new ArrayList<Expression>();
		list.add(new PlusExpression());
		list.add(new PlusExpression());
		list.add(new MinusExpression());
		list.add(new MinusExpression());
		list.add(new MinusExpression());
		list.add(new MinusExpression());
		
		for(Expression ex : list) {
			ex.interpret(context);
			System.out.println(context.getOutput());
		}
	}
}