
- 設計模式教程
- 設計模式 - 首頁
- 設計模式 - 概述
- 設計模式 - 工廠模式
- 抽象工廠模式
- 設計模式 - 單例模式
- 設計模式 - 建造者模式
- 設計模式 - 原型模式
- 設計模式 - 介面卡模式
- 設計模式 - 橋接模式
- 設計模式 - 過濾器模式
- 設計模式 - 組合模式
- 設計模式 - 裝飾器模式
- 設計模式 - 外觀模式
- 設計模式 - 享元模式
- 設計模式 - 代理模式
- 責任鏈模式
- 設計模式 - 命令模式
- 設計模式 - 直譯器模式
- 設計模式 - 迭代器模式
- 設計模式 - 中介者模式
- 設計模式 - 備忘錄模式
- 設計模式 - 觀察者模式
- 設計模式 - 狀態模式
- 設計模式 - 空物件模式
- 設計模式 - 策略模式
- 設計模式 - 模板模式
- 設計模式 - 訪問者模式
- 設計模式 - MVC模式
- 業務代表模式
- 組合實體模式
- 資料訪問物件模式
- 前端控制器模式
- 攔截過濾器模式
- 服務定位器模式
- 傳輸物件模式
- 設計模式資源
- 設計模式 - 問答
- 設計模式 - 快速指南
- 設計模式 - 有用資源
- 設計模式 - 討論
設計模式 - 策略模式
在策略模式中,類的行為或其演算法可以在執行時更改。這種設計模式屬於行為模式。
在策略模式中,我們建立表示各種策略的物件,以及一個上下文物件,其行為根據其策略物件而變化。策略物件改變了上下文物件的執行演算法。
實現
我們將建立一個定義操作的策略介面,以及實現策略介面的具體策略類。上下文是一個使用策略的類。
StrategyPatternDemo,我們的演示類,將使用上下文和策略物件來演示基於其部署或使用的策略的上下文行為變化。

步驟1
建立一個介面。
Strategy.java
public interface Strategy { public int doOperation(int num1, int num2); }
步驟2
建立實現同一介面的具體類。
OperationAdd.java
public class OperationAdd implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 + num2; } }
OperationSubstract.java
public class OperationSubstract implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 - num2; } }
OperationMultiply.java
public class OperationMultiply implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 * num2; } }
步驟3
建立上下文類。
Context.java
public class Context { private Strategy strategy; public Context(Strategy strategy){ this.strategy = strategy; } public int executeStrategy(int num1, int num2){ return strategy.doOperation(num1, num2); } }
步驟4
使用上下文檢視當它改變其策略時行為的變化。
StrategyPatternDemo.java
public class StrategyPatternDemo { public static void main(String[] args) { Context context = new Context(new OperationAdd()); System.out.println("10 + 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationSubstract()); System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationMultiply()); System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); } }
步驟5
驗證輸出。
10 + 5 = 15 10 - 5 = 5 10 * 5 = 50
廣告