There is a translator in the world of software, but we call it interpreter in software. If a particular type of problem occurs frequently in the system, it is necessary to express the examples of these problems as sentences in a language,
So you can build an interpreter and use that interpreter to interpret these sentences to solve these problems. Selector mode
First look at the class diagram.
Class diagram of Dahua design pattern
Let's look at the writer's example.
/** * content */ public class Context { private String text; public Context(String text) { super(); this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
/** * Abstract parent class */ public abstract class AbstractExpression { public void Interpret(Context context) { if (null != context.getText() && context.getText().length() > 0) { String keyValue = context.getText().substring(0, 2); String key = keyValue.substring(0, 1); String value = keyValue.substring(1, 2); excute(key, value); if (context.getText().length() > 2) { context.setText(context.getText().substring(3)); } else { context.setText(""); } } } public abstract void excute(String key, String value); }
/** * Capital escape */ public class CharacterExpression extends AbstractExpression{ @Override public void excute(String key, String value) { System.out.print(key.getBytes()[0] + Integer.parseInt(value) + " "); } }
/** * Small letter escape */ public class SmallExpression extends AbstractExpression { @Override public void excute(String key, String value) { int tar = key.getBytes()[0] + Integer.parseInt(value); System.out.print((char)tar + " "); } }
/** * client */ public class Text { public static void main(String[] args) { Context context = new Context("A1 B2 C3 D4 a1 b1 c1 d2"); AbstractExpression expression = null; while(context.getText().length() > 0) { String first = context.getText().substring(0, 1); if (Character.isLowerCase(first.charAt(0))) { expression = new SmallExpression(); } else { expression = new CharacterExpression(); } expression.Interpret(context); } } }
The operation results are as follows
66 68 70 72 b c d f
This is the author's understanding of the interpreter mode, hoping to help learn the interpreter mode.