源碼學習之設(shè)計模式(策略模式)

今天要給大家說的是策略模式。先不做解釋,先看代碼,體會一下策略模式的神奇。

修改前的代碼

public class Main {
    public static void main(String[] args) {
        String payType = "wxPay";
           if(payType.equals("alipay")){
               System.out.println("支付包支付");
           }else if(payType.equals("credit")){
               System.out.println("銀聯(lián)支付");
           }else if(payType.equals("netPay")){
               System.out.println("網(wǎng)銀支付");
           }else if(payType.equals("creditCard")){
               System.out.println("信用卡支付");
           }else{
               System.out.println("現(xiàn)金支付");
           }
    }
}

大家日常開發(fā)中一定見過類似上面的場景吧,寫了那么多if-else或者用switch-case,看著都讓人頭暈?,F(xiàn)在讓我們給他來個大變身吧。數(shù)碼寶貝究極進化。

修改后的代碼

首先定義一個支付策略接口,所有的支付方法都應實現(xiàn)此接口。

public interface PayStrategy {
    void doPay();
}

不同的支付方式的類實現(xiàn)上述接口,各個類結(jié)構(gòu)為

public class AliPay implements PayStrategy {
    @Override
    public void doPay() {
        System.out.println("支付寶支付");
    }
}


public class CreditCardPay implements PayStrategy {
    @Override
    public void doPay() {
        System.out.println("信用卡支付");
    }
}


public class CreditPay implements PayStrategy {
    @Override
    public void doPay() {
        System.out.println("銀聯(lián)支付");
    }
}



public class MoneyPay implements PayStrategy {
    @Override
    public void doPay() {
        System.out.println("現(xiàn)金支付");
    }
}



public class NetPay implements PayStrategy {
    @Override
    public void doPay() {
        System.out.println("網(wǎng)銀支付");
    }
}



public class WxPay implements PayStrategy {
    @Override
    public void doPay() {
        System.out.println("微信支付");
    }
}

在定義一個類管理策略,作為上下文。

public class PayContext {
    private PayStrategy payStrategy;

    public PayContext(PayStrategy payStrategy){
        this.payStrategy = payStrategy;
    }
    public void executePay (){
        payStrategy.doPay();
    }
}

此處呢,可以根據(jù)需要使用單例模式去定義這個類,保證全局的唯一性。

測試結(jié)果如下:

file

總結(jié)

。策略模式的優(yōu)點很明顯,可維護性和可讀性更好,方便以后擴展;然而缺點一眼就能看出:需要定義的類增多,對于對象的管理難度加大等。

類似上面的場景有很多,要根據(jù)實際情況選擇使用,并不一定非得要用策略模式,對于后期改動比較小的,選擇if-else或者switch-case顯然 是最優(yōu)的方案

說明

本文章為作者讀書筆記及感悟,其中參考了《spring5核心原理與30個類手寫實戰(zhàn)》以及互聯(lián)網(wǎng)上的內(nèi)容。如有錯誤,請評論或者私聊我,歡迎探討技術(shù)問題 。即將畢業(yè),在準備找工作,有朋友想給我介紹的,歡迎添加微信:sllbiao。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容