設計模式——23直譯器模式(Interpreter)

inzaghi1984發表於2017-12-11

23、直譯器模式(Interpreter)
直譯器模式是我們暫時的最後一講,一般主要應用在OOP開發中的編譯器的開發中,所以適用面比較窄。

Context類是一個上下文環境類,Plus和Minus分別是用來計算的實現,程式碼如下:

[java] view plaincopy

  1. public interface Expression {
  2. public int interpret(Context context);
  3. }
    [java] view plaincopy
  4. public class Plus implements Expression {
  5. @Override
  6. public int interpret(Context context) {
  7. return context.getNum1()+context.getNum2();
  8. }
  9. }
    [java] view plaincopy
  10. public class Minus implements Expression {
  11. @Override
  12. public int interpret(Context context) {
  13. return context.getNum1()-context.getNum2();
  14. }
  15. }
    [java] view plaincopy
  16. public class Context {
  17. private int num1;
  18. private int num2;
  19. public Context(int num1, int num2) {
  20. this.num1 = num1;
  21. this.num2 = num2;
  22. }
  23. public int getNum1() {
  24. return num1;
  25. }
  26. public void setNum1(int num1) {
  27. this.num1 = num1;
  28. }
  29. public int getNum2() {
  30. return num2;
  31. }
  32. public void setNum2(int num2) {
  33. this.num2 = num2;
  34. }
  35. }
    [java] view plaincopy
  36. public class Test {
  37. public static void main(String[] args) {
  38. // 計算9+2-8的值
  39. int result = new Minus().interpret((new Context(new Plus()
  40. .interpret(new Context(9, 2)), 8)));
  41. System.out.println(result);
  42. }
  43. }
    最後輸出正確的結果:3。

基本就這樣,直譯器模式用來做各種各樣的直譯器,如正規表示式等的直譯器等等!


相關文章