策略模式:定義一組算法,將每個算法都封裝起來,並且使它們之間可以互換.
舉個栗子:我們網購下單的時候,可以選擇多種支付方式,如支付寶,網銀,微信等,那麼支付方式就是一組算法.
代碼清單-1 支付策略
/**
* 支付策略
*/
public interface PayStrategy {
/** 支付方法 */
void pay();
}
代碼清單-2 微信支付
/**
* 微信支付方式
*/
public class WeiXinPayStrategy implements PayStrategy {
public void pay() {
System.out.println("正在使用微信支付方式...");
}
}
代碼清單-3 支付寶支付
/**
* 支付寶支付方式
*/
public class AlipayStrategy implements PayStrategy{
public void pay() {
System.out.println("正在使用支付寶支付方式...");
}
}
代碼清單-4 網銀支付
/**
* 網銀支付方式
*/
public class CyberBankPayStrategy implements PayStrategy {
public void pay() {
System.out.println("正在使用網銀支付方式...");
}
}
代碼清單-5 消費者
public class Custom {
public void buy(){
System.out.println("已購買一雙襪子,准備去支付...");
}
/** 可以支持多種支付方式 */
public void pay(PayStrategy payStrategy){
payStrategy.pay();
}
}
代碼清單-6 場景類
public class Client {
public static void main(String[] args) {
Custom custom = new Custom();
custom.buy();
//此處可以更換多種支付方式
PayStrategy weixinPay = new WeiXinPayStrategy();
custom.pay(weixinPay);
}
}
運行結果
已購買一雙襪子,准備去支付... 正在使用微信支付方式...