Java策略模式(Strategy Pattern)是一种行为设计模式,它允许再运行时动态选择算法的行为.策略模式通过将算法封装在可互换的策略对象中,使得客户端代码能够轻松地切换算法,而无需修改原始代码.在策略模式中,每个算法都被实现为一个单独的策略类,这些策略类都实现了相同的接口,从而允许它们在运行时互相替换.
在Java中,可以使用接口或抽象类来定义策略接口.然后对于每个算法,都可以创建一个具体的实现类来实现这个接口.客户端代码可以通过将不同的策略对象传递给上下文对象来选择不同的算法.
Java策略模式通常包括以下三种角色:
支付策略接口(Strategy)
public interface PaymentStrategy {/*** 支付** @param amount*/void pay(double amount);
}
微信支付和支付宝支付(ConcreteStrategy)
public class WechatPayment implements PaymentStrategy {private String username;private String password;public WechatPayment(String username, String password) {this.username = username;this.password = password;}/*** 支付** @param amount*/@Overridepublic void pay(double amount) {System.out.println("微信支付:" + amount + "元");}
}public class AliPayment implements PaymentStrategy{private String username;private String password;public AliPayment(String username, String password) {this.username = username;this.password = password;}/*** 支付** @param amount*/@Overridepublic void pay(double amount) {System.out.println("支付宝支付:" + amount + "元");}
}
购物车类(Context)
public class ShoppingCart {private List- itemList;private PaymentStrategy paymentStrategy;public ShoppingCart() {itemList = new ArrayList<>();}public void setPaymentStrategy(PaymentStrategy paymentStrategy) {this.paymentStrategy = paymentStrategy;}public void addItem(Item item){itemList.add(item);}public void removeItem(Item item){itemList.remove(item);}public double calculateTotal(){return itemList.stream().mapToDouble(Item::getPrice).sum();}public void pay(){paymentStrategy.pay(calculateTotal());}
}
商品类
@Data
public class Item {private String name;private double price;public Item(String name, double price) {this.name = name;this.price = price;}
}
测试
public class Demo {public static void main(String[] args) {ShoppingCart shoppingCart = new ShoppingCart();Item item1 = new Item("item1",10);Item item2 = new Item("item2",10);shoppingCart.addItem(item1);shoppingCart.addItem(item2);shoppingCart.setPaymentStrategy(new AliPayment("aliPayUsername","aliPayPassword"));shoppingCart.pay();shoppingCart.setPaymentStrategy(new WechatPayment("wechatUsername","wechatPassword"));shoppingCart.pay();}
}
上面代码演示了一个简单的策略模式实现.我们定义了一个PaymentStrategy接口,它表示所有支付方式的共同操作.我们还定义了两个实现该接口的具体类AliPayment和WechatPayment,它们分别表示使用支付宝和微信支付的操作.我们还定义了一个ShoppingCart类,该类使用PaymentStrategy接口来表示支付方式,并根据需要切换实际的支付方式.
在我们的Demo类中,我们创建了一个ShoppingCart对象,并添加了两个Item对象,我们然后选择使用AliPayment进行支付,并调用pay()方法.我们接下来又选择使用WechatPayment进行支付,并再次调用pay()方法.
这样,我们就可以轻松地在不同的支付方式之间进行切换,并根据需要添加新的支付方式.
优点
缺点
应用场景