912
技術社區[雲棲]
Java中的策略模式實例教程
策略模式是一種行為模式。用於某一個具體的項目有多個可供選擇的算法策略,客戶端在其運行時根據不同需求決定使用某一具體算法策略。
策略模式也被稱作政策模式。實現過程為,首先定義不同的算法策略,然後客戶端把算法策略作為它的一個參數。使用這種模式最好的例子是Collection.sort()方法了,它使用Comparator對象作為參數。根據Comparator接口不同實現,對象會被不同的方法排序。詳細介紹請看java中的排序對象。
本文例子是,完成一個簡單地購物車,兩種付款策略可供選擇,一為信用卡,另外一種為Paypal。
首先創建策略接口,在本文例子中,付款金額作為參數。
1 |
package com.journaldev.design.strategy;
|
3 |
public interface PaymentStrategy {
|
5 |
public void pay( int amount);
|
現在實現使用信用卡及Paypal兩種算法策略的實體類。
01 |
package com.journaldev.design.strategy;
|
03 |
public class CreditCardStrategy implements PaymentStrategy {
|
06 |
private String cardNumber;
|
08 |
private String dateOfExpiry;
|
10 |
public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){
|
12 |
this .cardNumber=ccNum;
|
14 |
this .dateOfExpiry=expiryDate;
|
17 |
public void pay( int amount) {
|
18 |
System.out.println(amount + " paid with credit/debit card" );
|
01 |
package com.journaldev.design.strategy;
|
03 |
public class PaypalStrategy implements PaymentStrategy {
|
05 |
private String emailId;
|
06 |
private String password;
|
08 |
public PaypalStrategy(String email, String pwd){
|
14 |
public void pay( int amount) {
|
15 |
System.out.println(amount + " paid using Paypal." );
|
此時,算法策略已經準備就緒,現在需要實現購物車以及能夠運用付款策略的支付方法。
01 |
package com.journaldev.design.strategy;
|
05 |
private String upcCode;
|
08 |
public Item(String upc, int cost){
|
13 |
public String getUpcCode() {
|
17 |
public int getPrice() {
|
01 |
package com.journaldev.design.strategy;
|
03 |
import java.text.DecimalFormat;
|
04 |
import java.util.ArrayList;
|
05 |
import java.util.List;
|
07 |
public class ShoppingCart {
|
12 |
public ShoppingCart(){
|
13 |
this .items= new ArrayList<Item>();
|
16 |
public void addItem(Item item){
|
20 |
public void removeItem(Item item){
|
21 |
this .items.remove(item);
|
24 |
public int calculateTotal(){
|
26 |
for (Item item : items){
|
27 |
sum += item.getPrice();
|
32 |
public void pay(PaymentStrategy paymentMethod){
|
33 |
int amount = calculateTotal();
|
34 |
paymentMethod.pay(amount);
|
注意,購物車的支付方法接受支付策略作為參數,但是不在其內部保存任何實例變量。
一個簡單地測試程序。
01 |
package com.journaldev.design.strategy;
|
03 |
public class ShoppingCartTest {
|
05 |
public static void main(String[] args) {
|
06 |
ShoppingCart cart = new ShoppingCart();
|
08 |
Item item1 = new Item( "1234" , 10 );
|
09 |
Item item2 = new Item( "5678" , 40 );
|
15 |
cart.pay( new PaypalStrategy( "myemail@example.com" , "mypwd" ));
|
18 |
cart.pay( new CreditCardStrategy( "Pankaj Kumar" , "1234567890123456" , "786" , "12/15" ));
|
輸出如下:
2 |
50 paid with credit/debit card
|
策略模式UML圖

重要點:
* 此處可以構建策略的實體變量,但是應該盡量避免這種情況。因為需要保證對於特定的任務能夠對應某個具體的算法策略,與Collection.sort()和Array.sort()方法使用comparator作為參數道理類似。
* 策略模式類似與狀態模式。兩者之間的不同,狀態模式中的Context(環境對象)包含了狀態的實例變量,並且不同的任務依賴同一個狀態。相反,在策略模式中策略是作為一個參數傳遞進方法中,context(環境對象)不需要也不能存儲任何變量。
* 當一組算法對應一個任務,並且程序可以在運行時靈活的選擇其中一個算法,策略模式是很好的選擇。
這就是全部的Java策略模式,希望你喜歡上它了。
最後更新:2017-05-23 11:31:48