《大话设计模式》第二十七章
package ch27;
public abstract class Expression {
public void interpret(PlayContext context) {
if (context.getContext().length() == 0) {
return;
} else {
String playKey = context.getContext().substring(0, 1);
if (context.getContext().length() > 1) {
context.setContext(context.getContext().substring(2));
int pos = context.getContext().indexOf(" ");
if (pos < context.getContext().length() && pos > -1) {
String sPlayValue = context.getContext().substring(0, pos);
int playValue = Integer.parseInt(sPlayValue);
int pos2 = context.getContext().indexOf(" ");
if (pos2 < context.getContext().length() && pos2 > -1) {
context.setContext(context.getContext().substring(pos2 + 1));
execute(playKey, playValue);
}
}
}
}
}
public abstract void execute(String key, int value);
}
package ch27;
public class Note extends Expression {
@Override
public void execute(String key, int value) {
String note = "";
if ("C".equalsIgnoreCase(key)) {
note = "1";
} else if ("D".equalsIgnoreCase(key)) {
note = "2";
} else if ("E".equalsIgnoreCase(key)) {
note = "3";
} else if ("F".equalsIgnoreCase(key)) {
note = "4";
} else if ("G".equalsIgnoreCase(key)) {
note = "5";
} else if ("A".equalsIgnoreCase(key)) {
note = "6";
} else if ("B".equalsIgnoreCase(key)) {
note = "7";
}
System.out.print(note + " ");
}
}
package ch27;
public class Scale extends Expression {
@Override
public void execute(String key, int value) {
String scale = "";
switch (value) {
case 1:
scale = "低音";
break;
case 2:
scale = "中音";
break;
case 3:
scale = "高音";
break;
}
System.out.print(scale + " ");
}
}
package ch27;
public class PlayContext {
private String context;
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
}
package ch27;
/**
* 解释器模式
* @author Administrator
*
*/
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
PlayContext context = new PlayContext();
String str = "O 2 E 0 G 0 A 3 E 0 G 0 D 3 E 0 G 0 A 0 O 3 C 1 O 2 A 0 G 1 C 0 E 0 D 3 ";
context.setContext(str);
Expression exp = null;
while (context.getContext().length() > 0) {
String str2 = context.getContext().substring(0, 1);
if ("O".equalsIgnoreCase(str2)) {
exp = new Scale();
} else {
exp = new Note();
}
exp.interpret(context);
}
}
}
运行:
中音 3 5 6 3 5 2 3 5 6 高音 1 中音 6 5 1 3 2
JDK里的java.text.Format及其子类、子孙类NumberFormat、DecimalFormat等是经典例子。