巧用策略模式实现if-else的判断
1、Strategy接口
public interface StrategyService {
String doOperation();
}
2、StrategyImpl实现类
import com.example.strategystudy.strategy.service.StrategyService;
import org.springframework.stereotype.Component;
@Component("Tencent")
public class StrategyTencentImpl implements StrategyService {
@Override
public String doOperation() {
return "print Tencent";
}
}
import com.example.strategystudy.strategy.service.StrategyService;
import org.springframework.stereotype.Component;
@Component("Wechat")
public class StrategyWechatImpl implements StrategyService {
@Override
public String doOperation() {
return "print Wechat";
}
}
3、将实现Strategy的实现类都自动注入到strategyMap类
import com.example.strategystudy.strategy.service.StrategyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class FactoryForStrategy {
@Autowired
private final Map<String, StrategyService> strategies = new ConcurrentHashMap<>();
public StrategyService getStrategy(String component) throws Exception{
StrategyService strategy = strategies.get(component);
if(strategy == null) {
throw new RuntimeException("no strategy defined");
}
return strategy;
}
}
4、测试结果
@Test
public void pattern(){
try {
String str = factoryForStrategy.getStrategy("Wechat").doOperation();
log.info("测试结果{}", str);
} catch (Exception e) {
log.error("error:{}", e.getMessage());
}
}