Java二十三設計模式之------解譯器式

來源:互聯網
上載者:User

標籤:set   解譯器   strong   href   ati   tac   設計模式   att   htm   

一、解譯器模式(Interpreter)
解譯器模式一般主要應用在OOP開發中的編譯器的開發中,所以適用面比較窄。

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

 

  1. public interface Expression {  
  2.     public int interpret(Context context);  
  3. }  
 
  1. public class Plus implements Expression {  
  2.   
  3.     @Override  
  4.     public int interpret(Context context) {  
  5.         return context.getNum1()+context.getNum2();  
  6.     }  
  7. }  
  1. public class Minus implements Expression {  
  2.   
  3.     @Override  
  4.     public int interpret(Context context) {  
  5.         return context.getNum1()-context.getNum2();  
  6.     }  
  7. }  
 
  1. public class Context {  
  2.       
  3.     private int num1;  
  4.     private int num2;  
  5.       
  6.     public Context(int num1, int num2) {  
  7.         this.num1 = num1;  
  8.         this.num2 = num2;  
  9.     }  
  10.       
  11.     public int getNum1() {  
  12.         return num1;  
  13.     }  
  14.     public void setNum1(int num1) {  
  15.         this.num1 = num1;  
  16.     }  
  17.     public int getNum2() {  
  18.         return num2;  
  19.     }  
  20.     public void setNum2(int num2) {  
  21.         this.num2 = num2;  
  22.     }  
  23.       
  24.       
  25. }  
 
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.   
  5.         // 計算9+2-8的值  
  6.         int result = new Minus().interpret((new Context(new Plus()  
  7.                 .interpret(new Context(9, 2)), 8)));  
  8.         System.out.println(result);  
  9.     }  
  10. }  

最後輸出正確的結果:3。

 

基本就這樣,解譯器模式用來做各種各樣的解譯器,如Regex等的解譯器等等!

轉載自 https://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html

Java二十三設計模式之------解譯器式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.