- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > 編程語(yǔ)言 >
- Java通俗易懂系列設計模式之策略模式
策略設計模式是行為設計模式之一。當我們?yōu)樘囟ㄈ蝿?wù)使用多個(gè)算法時(shí),使用策略模式,客戶(hù)端決定在運行時(shí)使用的實(shí)際實(shí)現。
策略模式的最佳示例之一是Collections.sort()采用Comparator參數的方法?;贑omparator接口的不同實(shí)現,對象將以不同的方式進(jìn)行排序。
對于我們的示例,我們將嘗試實(shí)施一個(gè)簡(jiǎn)單的購物車(chē),我們有兩種付款策略 - 使用信用卡或使用PayPal。
首先,我們將為我們的策略模式示例創(chuàng )建接口,在我們的例子中,支付金額作為參數傳遞。
支付方式:PaymentStrategy.java
package com.journaldev.design.strategy; public interface PaymentStrategy { public void pay(int amount); }
現在我們將不得不使用信用卡/借記卡或通過(guò)PayPal為支付創(chuàng )建具體的算法實(shí)現。
信用卡付款:CreditCardStrategy.java
package com.journaldev.design.strategy; public class CreditCardStrategy implements PaymentStrategy { private String name; private String cardNumber; private String cvv; private String dateOfExpiry; public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){ this.name=nm; this.cardNumber=ccNum; this.cvv=cvv; this.dateOfExpiry=expiryDate; } @Override public void pay(int amount) { System.out.println(amount +" paid with credit/debit card"); } }
Paypal付款:PaypalStrategy.java
package com.journaldev.design.strategy; public class PaypalStrategy implements PaymentStrategy { private String emailId; private String password; public PaypalStrategy(String email, String pwd){ this.emailId=email; this.password=pwd; } @Override public void pay(int amount) { System.out.println(amount + " paid using Paypal."); } }
現在我們的策略模式示例算法準備好了。我們可以實(shí)施購物車(chē)和付款方式將需要輸入作為付款策略。
package com.journaldev.design.strategy; public class Item { private String upcCode; private int price; public Item(String upc, int cost){ this.upcCode=upc; this.price=cost; } public String getUpcCode() { return upcCode; } public int getPrice() { return price; } }
ShoppingCart.java
package com.journaldev.design.strategy; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; public class ShoppingCart { //List of items List<Item> items; public ShoppingCart(){ this.items=new ArrayList<Item>(); } public void addItem(Item item){ this.items.add(item); } public void removeItem(Item item){ this.items.remove(item); } public int calculateTotal(){ int sum = 0; for(Item item : items){ sum += item.getPrice(); } return sum; } public void pay(PaymentStrategy paymentMethod){ int amount = calculateTotal(); paymentMethod.pay(amount); } }
請注意,購物車(chē)的付款方式需要付款算法作為參數,并且不會(huì )將其作為實(shí)例變量存儲在任何位置。
讓我們用一個(gè)簡(jiǎn)單的程序測試我們的策略模式示例設置。
ShoppingCartTest.java
package com.journaldev.design.strategy; public class ShoppingCartTest { public static void main(String[] args) { ShoppingCart cart = new ShoppingCart(); Item item1 = new Item("1234",10); Item item2 = new Item("5678",40); cart.addItem(item1); cart.addItem(item2); //pay by paypal cart.pay(new PaypalStrategy("myemail@example.com", "mypwd")); //pay by credit card cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15")); } }
上述程序的輸出是:
50 paid using Paypal.
50 paid with credit/debit card
我們可以使用組合為策略創(chuàng )建實(shí)例變量,但我們應該避免這種情況,因為我們希望將特定策略應用于特定任務(wù)。在Collections.sort()和Arrays.sort()方法中遵循相同的方法,將比較器作為參數。
策略模式與狀態(tài)模式(State Pattern)非常相似。其中一個(gè)區別是Context包含狀態(tài)作為實(shí)例變量,并且可以有多個(gè)任務(wù),其實(shí)現可以依賴(lài)于狀態(tài),而策略模式策略作為參數傳遞給方法,上下文對象沒(méi)有任何變量來(lái)存儲它。
當我們?yōu)樘囟ㄈ蝿?wù)提供多個(gè)算法時(shí),策略模式很有用,我們希望我們的應用程序可以靈活地在運行時(shí)為特定任務(wù)選擇任何算法。
以上就是Java通俗易懂系列設計模式之策略模式的詳細內容,更多關(guān)于Java設計模式的資料請關(guān)注腳本之家其它相關(guān)文章!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站