代碼調(diào)優(yōu)——利用策略模式優(yōu)化過多 if else 代碼

首先上實例代碼

if(a){
  //dosomething
}else if (b){
  //doshomething
}else if(c){   
  //doshomething
} else{   
  ////doshomething
}

這種大量的if else嵌套,邏輯會比較混亂,并且很容易出錯,比如這樣的

        if(SystemErrorCode.QUIT.getCode().equals(msg)){
            System.out.println(SystemErrorCode.QUIT.getCode());
        }else if(SystemErrorCode.ALL.getCode().equals(msg)){
            System.out.println(SystemErrorCode.ALL.getCode());
        }else if(SystemErrorCode.USER.getCode().equals(msg)){
            System.out.println(SystemErrorCode.USER.getCode());
        }else if(SystemErrorCode.ADMIN.getCode().equals(msg)){
            System.out.println(SystemErrorCode.ADMIN.getCode());
        }else if(SystemErrorCode.AI.getCode().equals(msg)){
            System.out.println(SystemErrorCode.AI.getCode());
        }else if(SystemErrorCode.QAI.getCode().equals(msg)){
            System.out.println(SystemErrorCode.QAI.getCode());
        }else if(SystemErrorCode.INFO.getCode().equals(msg)){
            System.out.println(SystemErrorCode.INFO.getCode());
        }else {
            System.out.println("nothing");
        }

剛開始條件比較少,現(xiàn)在功能多了,每次新增一個else條件都需要仔細的核對,防止對之前的邏輯有影響
這是修改過后的代碼

        InnerCommand instance = innerCommandContext.getInstance(msg);
        instance.process(msg);

整體思路如下:

  • 定義一個 InnerCommand 接口,其中有一個 process 函數(shù)交給具體的業(yè)務實現(xiàn)。
  • 根據(jù)自己的業(yè)務,會有多個類實現(xiàn) InnerCommand 接口;這些實現(xiàn)類都會注冊到 SpringBean 容器中供之后使用。
  • 通過客戶端輸入命令,從 SpringBean 容器中獲取一個 InnerCommand 實例。
  • 執(zhí)行最終的 process 函數(shù)。


    流程圖

    主要想實現(xiàn)的目的就是在有多個判斷條件,只需要根據(jù)當前msg的狀態(tài)動態(tài)的獲取 InnerCommand 實例。
    從源碼上來看最主要的就是 InnerCommandContext 類,他會根據(jù)當前命令動態(tài)獲取 InnerCommand 實例。

/**
 * @ProjectName: aServerAdmin
 * @Package: com.app
 * @ClassName: InnerCommandContext
 * @Description:求你了,寫點注釋吧
 * @Author: Kevin
 * @CreateDate: 18/2/15 下午3:32
 * @UpdateUser:
 * @UpdateDate: 18/2/15 下午3:32
 * @UpdateRemark:
 * @Version: 1.0
 */
public class InnerCommandContext {

    @Autowired
    ApplicationContext applicationContext;

    public InnerCommand getInstance(String command) {
        //getAllClazz
        Map<String, String> allClazz = SystemErrorCode.getAllClazz();
        String[] trim = command.trim().split(" ");
        String clazz = allClazz.get(trim[0]);
        InnerCommand innerCommand = null;
        try {
            if (StringUtils.isEmpty(clazz)) {
                clazz = null;
            }
            innerCommand = (InnerCommand) applicationContext.getBean(Class.forName(clazz));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return innerCommand;
    }
}
  • 第一步是獲取所有的 InnerCommand 實例列表。
  • 根據(jù)客戶端輸入的命令從第一步的實例列表中獲取類類型。
  • 根據(jù)類類型從 Spring 容器中獲取具體實例對象。
/**
 * @ClassName: SystemErrorCode
 * @Description: 枚舉
 * @Author: Kevin
 * @CreateDate: 18/2/15 下午5:31
 * @UpdateUser:
 * @UpdateDate: 18/2/15 下午5:31
 * @UpdateRemark: 更新項目
 * @Version: 1.0
 */
public enum SystemErrorCode {

    QUIT(":quit", "", "PrintQuitCommand"),
    ALL(":all", "", "PrintAllCommand"),
    USER(":user", "", "PrintUserCommand"),
    ADMIN(":admin", "", "PrintAdminCommand"),
    AI(":ai", "", "PrintAiCommand"),
    QAI(":qai", "", "PrintQaiCommand"),
    INFO(":info", "", "PrintInfoCommand");
    private String code;
    private String desc;
    private String clazz;
    private static final Map<String, String> err_desc = new HashMap<String, String>();

    static {
        for (SystemErrorCode refer : SystemErrorCode.values()) {
            err_desc.put(refer.getCode(), refer.getClazz());
        }
    }

    private SystemErrorCode(String code, String desc, String clazz) {
        this.code = code;
        this.desc = desc;
        this.clazz = clazz;
    }

    public static Map<String, String> getAllClazz() {
        return err_desc;
    }
    public static String getDescByCode(int code) {
        return err_desc.get(code);
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    public String getClazz() {
        return clazz;
    }
    public void setClazz(String clazz) {
        this.clazz = clazz;
    }
}
/**
 * @ProjectName: aServerAdmin
 * @Package: com.app.command
 * @ClassName: InnerCommand
 * @Description: 接口代碼
 * @Author: Kevin
 * @CreateDate: 18/2/15 下午3:24
 * @UpdateUser:
 * @UpdateDate: 18/2/15 下午3:24
 * @UpdateRemark:
 * @Version: 1.0
 */
public interface InnerCommand {
    void process(String msg);
}

/**
 * @ProjectName: aServerAdmin
 * @Package: com.app.service
 * @ClassName: PrintAdminCommand
 * @Description:示例
 * @Author: Kevin
 * @CreateDate: 18/2/15 下午5:06
 * @UpdateUser:
 * @UpdateDate: 18/2/15 下午5:06
 * @UpdateRemark:
 * @Version: 1.0
 */
@Service
public class PrintAdminCommand implements InnerCommand {
    @Override
    public void process(String msg) {

    }
}

最后編輯于
?著作權(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)容

  • 前言 本次來一點實際開發(fā)中會用到的小技巧。 比如平時大家是否都會寫類似這樣的代碼: if(a){//dosomet...
    程序員日常填坑閱讀 708評論 0 1
  • 一、Python簡介和環(huán)境搭建以及pip的安裝 4課時實驗課主要內(nèi)容 【Python簡介】: Python 是一個...
    _小老虎_閱讀 6,338評論 0 10
  • ¥開啟¥ 【iAPP實現(xiàn)進入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 7,355評論 0 17
  • 今天去了稅務局,第一次找專管員。也沒那么可怕,多去去就好了,實在不行還有公司呢。自己只要多去嘗試,多問,弄清楚就可...
    旎旎曉閱讀 344評論 0 0
  • 隨時準備說謝謝,就是要時刻有一顆感恩的心,活著就要感謝,這句話和公司“大家發(fā)”理念非常之相近。公司發(fā)展壯大...
    余建平閱讀 448評論 0 0

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