終:直譯器模式

weixin_34146805發表於2016-11-04

主要應用在OOP開發中的編譯器的開發中,所以適用面比較窄

Context類是一個上下文環境類,Plus和Minus分別是用來計算的實現,程式碼如下:
public interface Expression {  
    public int interpret(Context context);  
}
public class Plus implements Expression {  
  
    @Override  
    public int interpret(Context context) {  
        return context.getNum1()+context.getNum2();  
    }  
}
public class Minus implements Expression {  
  
    @Override  
    public int interpret(Context context) {  
        return context.getNum1()-context.getNum2();  
    }  
}
public class Context {  
      
    private int num1;  
    private int num2;  
      
    public Context(int num1, int num2) {  
        this.num1 = num1;  
        this.num2 = num2;  
    }  
      
    public int getNum1() {  
        return num1;  
    }  
    public void setNum1(int num1) {  
        this.num1 = num1;  
    }  
    public int getNum2() {  
        return num2;  
    }  
    public void setNum2(int num2) {  
        this.num2 = num2;  
    }  
} 
//測試
public class Test {  
  
    public static void main(String[] args) {  
        // 計算9+2-8的值  
        int result = new Minus().interpret((new Context(new Plus()  
                .interpret(new Context(9, 2)), 8)));  
        System.out.println(result);  
    }  
}
直譯器模式用來做各種各樣的直譯器,如正規表示式等的直譯器等等!

父文連結

相關文章