震惊!继结构模式,又一模式横出江湖!一起跟着小编来康康吧~
策略模式(Strategy)
适用场合
当你有多种算法来实现同一个任务,但需要根据client动态切换算法。
比如,当有二维数组和邻接表两种实现方式来存储一个图的vertex和edge时,程序能够识别边和点的关系,来判断是稀疏图还是密集图,从而更好的实现。
又比如,你需要排序一组数据,客户是用冒泡还是归并,亦或是快排?
思想
可以为不同的实现算法构造抽象接口,利用委托机制,在运行时动态传入client倾向的算法类实例
Advantage:
Easily extensible for new algorithm implementations
Separates algorithm from client context
实现
public class Item(){
String str;
int price;
public Item(String str, int price){
this.str = str;
this.price = price;
}
}
public interface PaymentStrategy{
public void pay(int amount);
}
public class ShoppingCart{
Item it;
...
public void pay(PaymentStrategy paymentMethod){
ibnt amount = calculateTotalk();
paymentMethod.pay(amount);
}
public void addItem(Item it){
this.it = it;
}
}
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, StringexpiryDate){
this.name = nm;
this.cardNumber