策略模式是属于行为型模式之一。当我们对一个具体的作业有多个算法可以调用时,策略模式使客户端用户决定实际上运行实现那个算法。
如果使用过MessageDigest.getInstance(String algorithm)这个方法获取一个MessageDigest对象的朋友,你可知道,这个就是一个标准的策略模式。根据algorithm算法名称来知道要调用那个算法,最后得到得到MessageDigest对象的实例。下面看一个简单的实例,UML图如下所示:
我们简单的实现一个购物车和两种不同的支付方式,分别是信用卡支付和银联支付。
定义一个策略模式的接口。
public interface PaymentStrategy {
public void pay(int amount);
}
创建信用卡的实现类。
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");
}
}
银联支付类。
public class UnionPalStrategy implements PaymentStrategy {
private String emailId;
private String password;
public UnionPalStrategy (String email, String pwd){
this.emailId=email;
this.password=pwd;
}
@Override
public void pay(int amount) {
System.out.println(amount + " paid using UnionPay.");
}
}
接下来,购物车中需要放置商品,定义一个商品项目类。
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;
}
}
购物车类
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);
}
}
一切类都定义好了,最后,测试这个设计模式。
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 UnionPaymentStrategy("myemail@example.com", "mypwd"));
//pay by credit card
cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"));
}
}
程序的输出结果:
50 paid using UnionPay.
50 paid with credit/debit card