1. 程式人生 > >大話設計模式二十七:直譯器模式(其實你不懂老闆的心)

大話設計模式二十七:直譯器模式(其實你不懂老闆的心)

直譯器模式:

        給定一中語言,定義它的文法的一種表示,並定義一個直譯器,這個直譯器使用該表示來解釋語言中的句子。

// 表示式類
public abstract class Expression {

	public void interpret(PlayContext context) {
		if (context.getContext().length() == 0) {
			return;
		} else {
			String playKey = context.getContext().substring(0, 1);
			context.setContext(context.getContext().substring(2));
			double playValue = Double.parseDouble(context.getContext().substring(0, context.getContext().indexOf(" ")));
			context.setContext(context.getContext().substring(context.getContext().indexOf(" ") + 1));

			excute(playKey, playValue);
		}
	}

	public abstract void excute(String key, double value);

}

// 音符類
public class Note extends Expression {

	@Override
	public void excute(String key, double value) {
		String note = null;
		if (key.equals("C"))
			note = "1";
		if (key.equals("D"))
			note = "2";
		if (key.equals("E"))
			note = "3";
		if (key.equals("F"))
			note = "4";
		if (key.equals("G"))
			note = "5";
		if (key.equals("A"))
			note = "6";
		if (key.equals("B"))
			note = "7";

		System.out.print(" " + note + " ");
	}

}

// 音階類
public class Scale extends Expression {

	@Override
	public void excute(String key, double value) {
		String scale = null;
		int intKey = (int) value;
		if (intKey == 1)
			scale = "low scale";
		if (intKey == 2)
			scale = "mid scale";
		if (intKey == 3)
			scale = "high scale";

		System.out.print(" " + scale + " ");
	}

}

// 演奏內容類
public class PlayContext {

	private String context;

	public String getContext() {
		return context;
	}

	public void setContext(String context) {
		this.context = context;
	}

}

// 客戶端
public class InterpreterMain {

	public static void main(String[] args) {
		PlayContext context = new PlayContext();
		String content = "O 2 E 0.5 G 0.5 A 3 E 0.5 G 0.5 D 3 E 0.5 G 0.5 A 0.5 O 3 C 1 O 2 A 0.5 G 1 C 0.5 E 0.5 D 3 ";
		context.setContext(content);

		Expression exp = null;
		try {
			while (context.getContext().length() > 0) {
				String str = context.getContext().substring(0, 1);

				if (str.equals("O")) {
					exp = new Scale();
				} else {
					exp = new Note();
				}
				exp.interpret(context);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

        用直譯器模式就如同你開發了一個程式語言或指令碼給自己或別人用。用瞭解釋器模式就意味著很容易改變和拓展文法,因為該模式使用類來表示文法規則,你可以使用繼承來改變和拓展該文法。