優化if...else...語句

来源:https://www.cnblogs.com/cjsblog/archive/2023/01/16/17055846.html
-Advertisement-
Play Games

寫代碼的時候經常遇到這樣的場景:根據某個欄位值來進行不同的邏輯處理。例如,不同的會員等級在購物時有不同的折扣力度。如果會員的等級很多,那麼代碼中與之相關的if...elseif...else...會特別長,而且每新增一種等級時需要修改原先的代碼。可以用策略模式來優化,消除這種場景下的if...els ...


寫代碼的時候經常遇到這樣的場景:根據某個欄位值來進行不同的邏輯處理。例如,不同的會員等級在購物時有不同的折扣力度。如果會員的等級很多,那麼代碼中與之相關的if...elseif...else...會特別長,而且每新增一種等級時需要修改原先的代碼。可以用策略模式來優化,消除這種場景下的if...elseif...else...,使代碼看起來更優雅。

首先,定義一個介面

/**
 * 會員服務
 */
public interface VipService {
    void handle();
}

然後,定義實現類

/**
 * 白銀會員
 */
public class SilverVipService implements VipService {
    @Override
    public void handle() {
        System.out.println("白銀");
    }
}

/**
 * 黃金會員
 */
public class GoldVipService implements VipService {
    @Override
    public void handle() {
        System.out.println("黃金");
    }
}

最後,定義一個工廠類,目的是當傳入一個會員等級後,返回其對應的處理類

public class VipServiceFactory {
    private static Map<String, VipService> vipMap = new ConcurrentHashMap<>();

    public static void register(String type, VipService service) {
        vipMap.put(type, service);
    }

    public static VipService getService(String type) {
        return vipMap.get(type);
    }
}

為了建立會員等級和與之對應的處理類之間的映射關係,這裡通常可以有這麼幾種處理方式:

方式一:實現類手動註冊

可以實現InitializingBean介面,或者在某個方法上加@PostConstruct註解

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * 白銀會員
 */
@Component
public class SilverVipService implements VipService, InitializingBean {
    @Override
    public void handle() {
        System.out.println("白銀");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        VipServiceFactory.register("silver", this);
    }
}

/**
 * 黃金會員
 */
@Component
public class GoldVipService implements VipService, InitializingBean {
    @Override
    public void handle() {
        System.out.println("黃金");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        VipServiceFactory.register("gold", this);
    }
}

方式二:從Spring容器中直接獲取Bean

public interface VipService {
    void handle();
    String getType();
}

/**
 * 白銀會員
 */
@Component
public class SilverVipService implements VipService {
    @Override
    public void handle() {
        System.out.println("白銀");
    }
    @Override
    public String getType() {
        return "silver";
    }
}

/**
 * 黃金會員
 */
@Component
public class GoldVipService implements VipService {
    @Override
    public void handle() {
        System.out.println("黃金");
    }
    @Override
    public String getType() {
        return "gold";
    }
}

/**
 * 上下文
 */
@Component
public class VipServiceFactory implements ApplicationContextAware {
    private static Map<String, VipService> vipMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, VipService> map = applicationContext.getBeansOfType(VipService.class);
        map.values().forEach(service -> vipMap.put(service.getType(), service));
    }

    public static VipService getService(String type) {
        return vipMap.get(type);
    }
}

/**
 * 測試
 */
@SpringBootTest
class DemoApplicationTests {
    @Test
    void contextLoads() {
        VipServiceFactory.getService("silver").handle();
    }
}

方式三:反射+自定義註解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MemberLevel {
    String value();
}

@MemberLevel("silver")
@Component
public class SilverVipService implements VipService {
    @Override
    public void handle() {
        System.out.println("白銀");
    }
}

@MemberLevel("gold")
@Component
public class GoldVipService implements VipService {
    @Override
    public void handle() {
        System.out.println("黃金");
    }
}

/**
 * 上下文
 */
@Component
public class VipServiceFactory implements ApplicationContextAware {
    private static Map<String, VipService> vipMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//        Map<String, VipService> map = applicationContext.getBeansOfType(VipService.class);
        Map<String, Object> map = applicationContext.getBeansWithAnnotation(MemberLevel.class);
        for (Object bean : map.values()) {
            if (bean instanceof VipService) {
                String type = bean.getClass().getAnnotation(MemberLevel.class).value();
                vipMap.put(type, (VipService) bean);
            }
        }
    }

    public static VipService getService(String type) {
        return vipMap.get(type);
    }
}

完整示例代碼

/**
 * 結算業務種類
 * @Author: ChengJianSheng
 * @Date: 2023/1/16
 */
@Getter
public enum SettlementBusiType {
    RE1011("RE1011", "轉貼現"),
    RE4011("RE4011", "買斷式貼現"),
    RE4021("RE4021", "回購式貼現"),
    RE4022("RE4022", "回購式貼現贖回");
//    ......

    private String code;
    private String name;

    SettlementBusiType(String code, String name) {
        this.code = code;
        this.name = name;
    }
}


/**
 * 結算處理器
 * @Author: ChengJianSheng
 * @Date: 2023/1/16
 */
public interface SettlementHandler {
    /**
     * 清算
     */
    void handle();

    /**
     * 獲取業務種類
     */
    SettlementBusiType getBusiType();
}


/**
 * 轉貼現結算處理
 */
@Component
public class RediscountSettlementHandler implements SettlementHandler {
    @Override
    public void handle() {
        System.out.println("轉貼現");
    }

    @Override
    public SettlementBusiType getBusiType() {
        return SettlementBusiType.RE1011;
    }
}


/**
 * 買斷式貼現結算處理
 */
@Component
public class BuyoutDiscountSettlementHandler implements SettlementHandler {
    @Override
    public void handle() {
        System.out.println("買斷式貼現");
    }

    @Override
    public SettlementBusiType getBusiType() {
        return SettlementBusiType.RE4011;
    }
}


/**
 * 預設處理器
 * @Author: ChengJianSheng
 * @Date: 2023/1/16
 */
@Component
public class DefaultSettlementHandler implements /*SettlementHandler,*/ ApplicationContextAware {
    private static Map<SettlementBusiType, SettlementHandler> allHandlerMap = new ConcurrentHashMap<>();

    public static SettlementHandler getHandler(SettlementBusiType busiType) {
        return allHandlerMap.get(busiType);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, SettlementHandler> map = applicationContext.getBeansOfType(SettlementHandler.class);
        map.values().forEach(e -> allHandlerMap.put(e.getBusiType(), e));
    }
}


@SpringBootTest
class Demo2023ApplicationTests {
    @Test
    void contextLoads() {
        // 收到結算結果通知,根據業務種類進行結算處理
        SettlementHandler handler = DefaultSettlementHandler.getHandler(SettlementBusiType.RE1011);
        if (null != handler) {
            handler.handle();
        }
    }
}

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • StringBuilder類 一、結構剖析 一個可變的字元序列。此類提供一個與 StringBuffer 相容的 API,但不保證同步(StringBuilder 不是線程安全的)。該類被設計用作 StringBuffer 的一個簡易替換,==用在字元串緩衝區被單個線程使用的時候==。如果可能,建議 ...
  • Typora軟體與Markdown語法 Typora軟體的安裝 ​ ==Typora是什麼軟體:== ​ Typora是一款很火的輕量級支持Markdown語法的文本編輯器 ​ ==Typora下載:== ​ mac:https://mac.qdrayst.com/02/Typora_1.1.4_m ...
  • pycharm下載安裝與基本配置 1.簡介 PyCharm是一種Python IDE(Integrated Development Environment,集成開發環境),帶有一整套可以幫助用戶在使用Python語言開發時提高其效率的工具,比如調試、語法高亮、項目管理、代碼跳轉、智能提示、自動完成、 ...
  • 原創:扣釘日記(微信公眾號ID:codelogs),歡迎分享,轉載請保留出處。 簡介 最近我觀察到一個現象,當服務的請求量突發的增長一下時,服務的有效QPS會下降很多,有時甚至會降到0,這種現象網上也偶有提到,但少有解釋得清楚的,所以這裡來分享一下問題成因及解決方案。 隊列延遲 目前的Web伺服器, ...
  • CF鏈接:Least Prefix Sum Luogu鏈接:Least Prefix Sum $ {\scr \color {CornflowerBlue}{\text{Solution}}} $ 先來解釋一下題意: 給定一個數組,問最少把多少個數變成相反數,使得$ \forall \cal{i}$ ...
  • Spring管理Bean-IOC 1.Spring配置/管理bean介紹 Bean管理包括兩方面: 創建bean對象 給bean註入屬性 Bean的配置方式: 基於xml文件配置方式 基於註解配置方式 2.基於XML配置bean 2.1通過類型來獲取bean 通過id來獲取bean在Spring基本 ...
  • 1、yaml文件準備 common: secretid: AKIDxxxxx secretKey: 3xgGxxxx egion: ap-guangzhou zone: ap-guangzhou-7 InstanceChargeType: POSTPAID_BY_HOUR 2、config配置類準備 ...
  • 簡介 Netflix Eureka是微服務系統中最常用的服務發現組件之一,非常簡單易用。當客戶端註冊到Eureka後,客戶端可以知道彼此的hostname和埠等,這樣就可以建立連接,不需要配置。 Eureka 服務端 添加Maven依賴: <dependency> <groupId>org.spr ...
一周排行
    -Advertisement-
    Play Games
  • C#TMS系統代碼-基礎頁面BaseCity學習 本人純新手,剛進公司跟領導報道,我說我是java全棧,他問我會不會C#,我說大學學過,他說這個TMS系統就給你來管了。外包已經把代碼給我了,這幾天先把增刪改查的代碼背一下,說不定後面就要趕鴨子上架了 Service頁面 //using => impo ...
  • 委托與事件 委托 委托的定義 委托是C#中的一種類型,用於存儲對方法的引用。它允許將方法作為參數傳遞給其他方法,實現回調、事件處理和動態調用等功能。通俗來講,就是委托包含方法的記憶體地址,方法匹配與委托相同的簽名,因此通過使用正確的參數類型來調用方法。 委托的特性 引用方法:委托允許存儲對方法的引用, ...
  • 前言 這幾天閑來沒事看看ABP vNext的文檔和源碼,關於關於依賴註入(屬性註入)這塊兒產生了興趣。 我們都知道。Volo.ABP 依賴註入容器使用了第三方組件Autofac實現的。有三種註入方式,構造函數註入和方法註入和屬性註入。 ABP的屬性註入原則參考如下: 這時候我就開始疑惑了,因為我知道 ...
  • C#TMS系統代碼-業務頁面ShippingNotice學習 學一個業務頁面,ok,領導開完會就被裁掉了,很突然啊,他收拾東西的時候我還以為他要旅游提前請假了,還在尋思為什麼回家連自己買的幾箱飲料都要叫跑腿帶走,怕被偷嗎?還好我在他開會之前拿了兩瓶芬達 感覺感覺前面的BaseCity差不太多,這邊的 ...
  • 概述:在C#中,通過`Expression`類、`AndAlso`和`OrElse`方法可組合兩個`Expression<Func<T, bool>>`,實現多條件動態查詢。通過創建表達式樹,可輕鬆構建複雜的查詢條件。 在C#中,可以使用AndAlso和OrElse方法組合兩個Expression< ...
  • 閑來無聊在我的Biwen.QuickApi中實現一下極簡的事件匯流排,其實代碼還是蠻簡單的,對於初學者可能有些幫助 就貼出來,有什麼不足的地方也歡迎板磚交流~ 首先定義一個事件約定的空介面 public interface IEvent{} 然後定義事件訂閱者介面 public interface I ...
  • 1. 案例 成某三甲醫預約系統, 該項目在2024年初進行上線測試,在正常運行了兩天後,業務系統報錯:The connection pool has been exhausted, either raise MaxPoolSize (currently 800) or Timeout (curren ...
  • 背景 我們有些工具在 Web 版中已經有了很好的實踐,而在 WPF 中重新開發也是一種費時費力的操作,那麼直接集成則是最省事省力的方法了。 思路解釋 為什麼要使用 WPF?莫問為什麼,老 C# 開發的堅持,另外因為 Windows 上已經裝了 Webview2/edge 整體打包比 electron ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...