InitializingBean接口為bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是繼承該接口的類,在初始化bean的時候都會執(zhí)行該方法。
前言
在實(shí)際開發(fā)過程中經(jīng)常會出現(xiàn)行為不同的實(shí)現(xiàn),比如支付,那可能是微信支付,阿里支付,銀聯(lián)等支付的具體實(shí)現(xiàn)。要你用一個設(shè)計(jì)模式來實(shí)現(xiàn)
定義
策略模式定義了一系列算法,并將每個算法封裝起來,使他們可以相互替換,且算法的變化不會影響到使用算法的客戶
UML類圖

具體實(shí)現(xiàn)
InitializingBean接口說明
1、InitializingBean接口為bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是繼承該接口的類,在初始化bean的時候都會執(zhí)行該方法。
2、spring初始化bean的時候,如果bean實(shí)現(xiàn)了InitializingBean接口,會自動調(diào)用afterPropertiesSet方法。
3、在Spring初始化bean的時候,如果該bean實(shí)現(xiàn)了InitializingBean接口,并且同時在配置文件中指定了init-method,系統(tǒng)則是先調(diào)用afterPropertieSet()方法,然后再調(diào)用init-method中指定的方法。
策略工廠
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class StrategyFactory {
private static final Map<String, PayService> serviceMap = new ConcurrentHashMap<>();
public static void register(PayTypeEnum payTypeEnum, PayService service){
serviceMap.put(payTypeEnum.getType(), service);
}
public static Boolean getService(String payType){
PayService payService = serviceMap.get(payType);
if(payService!=null){
return payService.pay(payType);
}
return Boolean.FALSE;
}
}
支付枚舉
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum PayTypeEnum {
WX("wx", "微信"),
ZFB("zfb","支付寶支付"),;
private String type;
private String desc;
}
具體業(yè)務(wù)類
1、支付入口
public interface PayService {
Boolean pay(String payType);
}
2、支付入口具體實(shí)現(xiàn)
微信支付邏輯
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class WxPayService implements PayService, InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
StrategyFactory.register(PayTypeEnum.WX,this);
}
@Override
public Boolean pay(String payType){
log.info("調(diào)用微信支付");
return true;
}
}
阿里支付具體邏輯
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class AliPayService implements PayService, InitializingBean {
@Override
public void afterPropertiesSet(){
StrategyFactory.register(PayTypeEnum.ZFB, this);
}
@Override
public Boolean pay(String payType){
log.info("調(diào)用阿里支付");
return true;
}
}
3、定義一個控制器測試
import com.example.demo.celuemoshi.StrategyFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PayController {
@GetMapping("pay/{type}")
public boolean pay(@PathVariable("type") String type){
StrategyFactory.getService(type);
return true;
}
}
測試結(jié)果
測試微信支付:http://localhost:10001/pay/wx

測試阿里支付:http://localhost:10001/pay/zfb
