Java 中的策略设计模式 - 示例教程

策略设计模式是行为设计模式之一,当我们为特定任务使用多个算法,客户决定在运行时使用实际实现时,则使用策略模式。

战略模式

strategy pattern, strategy design pattern Strategy pattern is also known as Policy Pattern. We define multiple algorithms and let client application pass the algorithm to be used as a parameter. One of the best example of strategy pattern is Collections.sort() method that takes Comparator parameter. Based on the different implementations of Comparator interfaces, the Objects are getting sorted in different ways. For our example, we will try to implement a simple Shopping Cart where we have two payment strategies - using Credit Card or using PayPal. First of all we will create the interface for our strategy pattern example, in our case to pay the amount passed as argument. PaymentStrategy.java

1package com.journaldev.design.strategy;
2
3public interface PaymentStrategy {
4
5    public void pay(int amount);
6}

现在我们将不得不创建具体的实现用信用卡 / 借记卡或通过PayPal支付算法。

 1package com.journaldev.design.strategy;
 2
 3public class CreditCardStrategy implements PaymentStrategy {
 4
 5    private String name;
 6    private String cardNumber;
 7    private String cvv;
 8    private String dateOfExpiry;
 9    
10    public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){
11    	this.name=nm;
12    	this.cardNumber=ccNum;
13    	this.cvv=cvv;
14    	this.dateOfExpiry=expiryDate;
15    }
16    @Override
17    public void pay(int amount) {
18    	System.out.println(amount +" paid with credit/debit card");
19    }
20
21}

主页 > 支付策略.java

 1package com.journaldev.design.strategy;
 2
 3public class PaypalStrategy implements PaymentStrategy {
 4
 5    private String emailId;
 6    private String password;
 7    
 8    public PaypalStrategy(String email, String pwd){
 9    	this.emailId=email;
10    	this.password=pwd;
11    }
12    
13    @Override
14    public void pay(int amount) {
15    	System.out.println(amount + " paid using Paypal.");
16    }
17
18}

现在我们的策略模式示例算法已经准备好了,我们可以实施购物车,付款方式将需要作为付款策略输入。

 1package com.journaldev.design.strategy;
 2
 3public class Item {
 4
 5    private String upcCode;
 6    private int price;
 7    
 8    public Item(String upc, int cost){
 9    	this.upcCode=upc;
10    	this.price=cost;
11    }
12
13    public String getUpcCode() {
14    	return upcCode;
15    }
16
17    public int getPrice() {
18    	return price;
19    }
20    
21}

购物网站:Java

 1package com.journaldev.design.strategy;
 2
 3import java.text.DecimalFormat;
 4import java.util.ArrayList;
 5import java.util.List;
 6
 7public class ShoppingCart {
 8
 9    //List of items
10    List<Item> items;
11    
12    public ShoppingCart(){
13    	this.items=new ArrayList<Item>();
14    }
15    
16    public void addItem(Item item){
17    	this.items.add(item);
18    }
19    
20    public void removeItem(Item item){
21    	this.items.remove(item);
22    }
23    
24    public int calculateTotal(){
25    	int sum = 0;
26    	for(Item item : items){
27    		sum += item.getPrice();
28    	}
29    	return sum;
30    }
31    
32    public void pay(PaymentStrategy paymentMethod){
33    	int amount = calculateTotal();
34    	paymentMethod.pay(amount);
35    }
36}

请注意,购物车的付款方式需要支付算法作为参数,并且不会将其存储在任何地方作为实例变量。

 1package com.journaldev.design.strategy;
 2
 3public class ShoppingCartTest {
 4
 5    public static void main(String[] args) {
 6    	ShoppingCart cart = new ShoppingCart();
 7    	
 8    	Item item1 = new Item("1234",10);
 9    	Item item2 = new Item("5678",40);
10    	
11    	cart.addItem(item1);
12    	cart.addItem(item2);
13    	
14    	//pay by paypal
15    	cart.pay(new PaypalStrategy("[email protected]", "mypwd"));
16    	
17    	//pay by credit card
18    	cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"));
19    }
20
21}

上述方案的结果是:

150 paid using Paypal.
250 paid with credit/debit card

战略设计模式 类图

Strategy Pattern, Strategy Design pattern in java

战略设计模式 重要点

  • 我们可以使用组合来创建策略的实例变量,但我们应该避免这样做,因为我们希望具体的策略应用于特定任务。同样在 Collections.sort() 和 Arrays.sort() 方法中使用比较器作为参数 *策略模式非常类似于 状态模式。 其中一个区别是,背景包含状态作为实例变量,并且可能有多个任务,其实施可以取决于状态,而在策略模式中通过了关于方法的论证,并且对象没有任何可存储变量 *策略模式是有用的,当我们有多个任务特定的算法,我们希望我们的应用能够灵活

这就是Java中的策略模式,我希望你喜欢它。

Published At
Categories with 技术
comments powered by Disqus