1. 程式人生 > 實用技巧 >策略模式(ConcurrencyLevel)併發使用者數

策略模式(ConcurrencyLevel)併發使用者數

策略模式:定義了一系列的演算法,並將每一個演算法封裝起來,而且使它們還可以相互替換。策略模式讓演算法獨立於使用它的客戶而獨立變化。

策略模式

策略模式在Spring的使用場景

把多重if判斷分割成多個不同的物件管理

  • ApplicationContext

FileSystemXmlApplicationContext
ClassPathXmlApplicationContext
XmlWebApplicationContext
……

  • Resource

UrlResource:訪問網路資源的實現類。
ClassPathResource:訪問類載入路徑裡資源的實現類。
FileSystemResource:訪問檔案系統裡資源的實現類。
ServletContextResource:訪問相對於 ServletContext 路徑裡的資源的實現類:
InputStreamResource:訪問輸入流資源的實現類。
ByteArrayResource:訪問位元組陣列資源的實現類。

  • 初始化策略:
    SimpleInstantiationStrategy 簡單初始化策略
    CglibSubclassingInstantiationStrategy CGLIB初始化策略

策略模式優缺點

優點:
1、避免對原有多重if條件的原始碼修改;
2、策略演算法可以自由切換;
3、擴充套件性好

缺點:
1、所有的策略都需要暴露給外面;
2、需要配合工廠模式或代理模式;
3、程式碼量增加

策略模式實現方式核心程式碼

public interface PayStrategy {
    /**
     * 共同演算法實現骨架
     * @return
     */
     public String toPayHtml();
}
@Component
public class AliPayStrategy  implements PayStrategy {
    @Override
    public String toPayHtml() {
        return "呼叫支付寶支付介面";
    }
}

1)、列舉+反射

public enum PayEnumStrategy {

    /**
     *  支付寶支付【也可以配置容器中的ID】
     */
    ALI_PAY("com.jarye.strategy.impl.AliPayStrategy"),
    /**
     *  銀聯支付【也可以配置容器中的ID】
     */
    UNION_PAY("com.jarye.strategy.impl.UnionPayStrategy");
    PayEnumStrategy(String className) {
        this.setClassName(className);
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    /**
     * class完整地址
     */
    private String className;

}
public static PayStrategy getPayStrategy(String strategyType) {
    try {
        // 1.獲取列舉中className
        String className = PayEnumStrategy.valueOf(strategyType).getClassName();
        // 2.使用java反射技術初始化類【也可以根據容器中的ID獲取bean】
        return (PayStrategy) Class.forName(className).newInstance();
    } catch (Exception e) {
        return null;
    }
}

2)、資料庫配置

// 1.使用PayCode查詢
PaymentChannelEntity paymentChannel = paymentChannelMapper.getPaymentChannel(payCode);
if(paymentChannel==null){
    return  "該渠道為空...";
}
// 2.獲取策略執行的beanid
String strategyBeanId = paymentChannel.getStrategyBeanId();
// 3.使用strategyBeanId獲取對應spring容器bean資訊
PayStrategy payStrategy = springUtils.getBean(strategyBeanId, PayStrategy.class);