在springboot项目中使用策略工厂模式
策略接口类
package cn.test.ext;
public interface ITestStrategy {
void execTestMethod();
}
策略实现类
package cn.test.ext.beanlife;
import cn.test.ext.ITestStrategy;
import cn.test.ext.MyStrategyFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class TestInitializingBean implements ITestStrategy, InitializingBean {
private static String str ;
@Override
public void afterPropertiesSet() throws Exception {
str = "qwe123!";
MyStrategyFactory.register("k1",this);
log.info("注册了策略:{}到策略工厂里",this);
}
@Override
public void execTestMethod() {
log.info("start----执行k1策略...");
System.err.println(str);
}
}
策略工厂类
package cn.test.ext;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
@Slf4j
public class MyStrategyFactory {
private static Map<String, ITestStrategy> strategyMap = new ConcurrentHashMap<>();
public static void register(String strategyCode, ITestStrategy itemStrategy) {
strategyMap.put(strategyCode, itemStrategy);
}
public static ITestStrategy getReceiptHandleStrategy(String key) {
for (String strate : strategyMap.keySet()) {
if (StrUtil.equals(strate, key)) {
ITestStrategy strategy = strategyMap.get(key);
log.info("拿到了策略:{}", strategy.getClass().getName());
return strategy;
}
}
log.info("没拿到对应的策略类,不存在 策略:{}", key);
return null;
}
}
策略上下文类
package cn.test.ext;
import org.springframework.stereotype.Component;
@Component
public class MyStrategyContext {
private ITestStrategy iTestStrategy;
public void getStrategyInstance(String key) {
ITestStrategy strategyInstance = MyStrategyFactory.getReceiptHandleStrategy(key);
this.iTestStrategy = strategyInstance;
}
public void execMethod(){
if (iTestStrategy!=null){
iTestStrategy.execTestMethod();
}
}
}