Reprint Please specify source: http://blog.csdn.net/lhy_ycu/article/details/40019829
Interpreter mode (interpreter): It defines what values will be obtained after an object has performed some sort of action with the object. It is generally used in the development of the compiler in OOP development, so the application surface is rather narrow.
First, UML modeling:
Second, the Code implementation
/** * Interpreter mode (interpreter): It defines what values will be obtained after an object has done something with the object. * * Generally used in the development of OOP development of the compiler, so the application surface is relatively narrow. * Example: Define an entity class first, encapsulating two variables num1, num2 */class entity {private Double num1;private double num2;public entity (double NUM1, double num2) {this.num1 = num1;this.num2 = num2;} Public double GetNum1 () {return NUM1;} public void SetNum1 (double num1) {this.num1 = NUM1;} Public double getNum2 () {return num2;} public void setNum2 (double num2) {this.num2 = num2;}} /** * Arithmetic interface */interface operatable {public double Interpreter (entity entity); /** * Addition Operation */class Addoperation implements operatable {@Overridepublic double interpreter (Entity entity) {return entity.ge TNUM1 () + entity.getnum2 ();}} /** * Subtraction Operation */class Minusoperation implements operatable {@Overridepublic double interpreter (Entity entity) {return entity. GETNUM1 ()-entity.getnum2 ();}} /** * Client Test class * * @author Leo */public class Test {public static void main (string[] args) {/** * Create addition, subtraction operation */addoperation Addoperation = new Addoperation (); Minusoperation Minusoperation = new minusoperation ();/** * One, step operation */double Addresult = addoperation.interpreter (new Entity);d ouble Minusresult = Minusoperation.interpreter (New Entity (20, 30)); System.out.println ("Addresult =" + Addresult); System.out.println ("Minusresult =" + Minusresult);/** * Two, mixed operation */double mixresult = new Addoperation (). Interpreter (New En Tity (Addoperation.interpreter (new entity), Minusoperation.interpreter (new entity (40, 50))); System.out.println ("Mixresult =" + Mixresult);}}
Iii. Summary
The interpreter pattern is used to make a variety of interpreters, such as the interpreter of regular expressions and so on.
Java Design Patterns Rookie series (20) The modeling and implementation of the interpreter pattern