利用接口作為參數(策略模式核心思想),實現可擴展的計算器,支援四則運算。
ComputeUseCompute 接收策略對象執行運算// 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這是策略模式最經典的入門級應用,展示了「面向接口編程」與「組合優於繼承」的設計智慧。