首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 接口實戰:策略模式實現計算器(加減乘除)

     編輯:Java 綜合教學

Java 接口實戰:策略模式實現計算器(加減乘除)

利用接口作為參數(策略模式核心思想),實現可擴展的計算器,支援四則運算。

設計結構

  1. 定義運算接口 Compute
  2. 四個實現類分別實現 + - * /
  3. 工具類 UseCompute 接收策略對象執行運算
  4. 測試類驗證功能

完整代碼

// 1. 運算接口
public interface Compute {
    int computer(int m, int n);
}

// 2. 四則運算實現
public class Add implements Compute {
    @Override public int computer(int m, int n) { return m + n; }
}
public class Subtract implements Compute {
    @Override public int computer(int m, int n) { return m - n; }
}
public class Multiply implements Compute {
    @Override public int computer(int m, int n) { return m * n; }
}
public class Divide implements Compute {
    @Override public int computer(int m, int n) { return m / n; }
}

// 3. 策略執行器
public class UseCompute {
    public void useCom(Compute com, int one, int two) {
        int result = com.computer(one, two);
        System.out.println("結果 = " + result);
    }

    public static void main(String[] args) {
        UseCompute calc = new UseCompute();
        calc.useCom(new Add(),      150, 33);  // 183
        calc.useCom(new Subtract(), 150, 33);  // 117
        calc.useCom(new Multiply(), 150, 33);  // 4950
        calc.useCom(new Divide(),   150, 33);  // 4
    }
}

運行結果

計算器運行結果

核心優勢

  • 開閉原則:新增運算(如取模、冪次)只需新增實現類,無需修改 UseCompute
  • 單一職責:每個運算邏輯獨立封裝
  • 運行時切換:可動態注入不同策略

這是策略模式最經典的入門級應用,展示了「面向接口編程」與「組合優於繼承」的設計智慧。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved