設計模式——23直譯器模式(Interpreter)
23、直譯器模式(Interpreter)
直譯器模式是我們暫時的最後一講,一般主要應用在OOP開發中的編譯器的開發中,所以適用面比較窄。
Context類是一個上下文環境類,Plus和Minus分別是用來計算的實現,程式碼如下:
[java] view plaincopy
- public interface Expression {
- public int interpret(Context context);
- }
[java] view plaincopy - public class Plus implements Expression {
- @Override
- public int interpret(Context context) {
- return context.getNum1()+context.getNum2();
- }
- }
[java] view plaincopy - public class Minus implements Expression {
- @Override
- public int interpret(Context context) {
- return context.getNum1()-context.getNum2();
- }
- }
[java] view plaincopy - 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;
- }
- }
[java] view plaincopy - 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);
- }
- }
最後輸出正確的結果:3。
基本就這樣,直譯器模式用來做各種各樣的直譯器,如正規表示式等的直譯器等等!
相關文章
- 設計模式的征途—23.直譯器(Interpreter)模式設計模式
- 設計模式--直譯器模式Interpreter(行為型)設計模式
- Rust語言之GoF設計模式: 直譯器Interpreter模式RustGo設計模式
- 直譯器模式(Interpreter)模式
- 23種設計模式之直譯器模式設計模式
- PHP設計模式(二十二)—直譯器模式(Interpreter PattPHP設計模式
- 設計模式之直譯器模式設計模式
- 設計模式(十五):直譯器模式設計模式
- 簡說設計模式——直譯器模式設計模式
- 極簡設計模式-直譯器模式設計模式
- Python設計模式-直譯器模式Python設計模式
- JAVA設計模式之直譯器模式Java設計模式
- 設計模式--直譯器模式和狀態模式設計模式
- 設計模式(十五)直譯器設計模式
- 折騰Java設計模式之直譯器模式Java設計模式
- 20.java設計模式之直譯器模式Java設計模式
- 軟體設計模式系列之十七——直譯器模式設計模式
- 直譯器設計模式知識概括設計模式
- 直譯器模式(Interpreter)2——跟著cc學設計系列模式
- 直譯器模式模式
- 終:直譯器模式模式
- 設計模式 第十章 備忘錄模式、直譯器模式、狀態模式設計模式
- Java設計模式-17、直譯器模式-自定義語言的實現Java設計模式
- 24_直譯器模式模式
- 23天設計模式之迭代器模式設計模式
- 23種設計模式之迭代器模式設計模式
- 設計模式學習筆記(二十二)直譯器模式及其實現設計模式筆記
- 設計模式(二十一)——直譯器模式(Spring 框架中SpelExpressionParser原始碼分析)設計模式Spring框架Express原始碼
- 23種設計模式(三)--裝飾器模式設計模式
- 23種設計模式(二)---策略設計模式設計模式
- 23種設計模式(八)-原型設計模式設計模式原型
- 23天設計模式之代理模式設計模式
- 23種設計模式(四)-代理模式設計模式
- 23種設計模式(7)-代理模式設計模式
- 23種設計模式之策略模式設計模式
- 23種設計模式之命令模式設計模式
- 23種設計模式(四)- 模板方法設計模式設計模式
- 23種設計模式(七)-狀態設計模式設計模式