策略模式属于行为型模式,行为型用来识别对象之间的常用交流模式并加以实现。使用策略模式的好处有三点:
1,优化代码逻辑结构性,可以减少分支判断。
2,增加代码程序拓展和移植。
3,增加代码复用和业务逻辑分离和优化。
当然也有缺点的,缺点就是得提前约定好规范,从而触发这样的业务场景。
1、调用方式
private final Map<String,TestService> testServiceMap;
private final ApplicationContext context;
@GetMapping("/test")
public CommonResult<String> test(@RequestParam("route") TestRoute route){
//调用方式一
//return CommonResult.success(testServiceMap.get(route.name()).value());
//调用方式二
return CommonResult.success(context.getBean(route.name(),TestService.class).value());
}
2、类型枚举类
/**
* 类型枚举类
* @date 2023/10/18 14:03
* @author luohao
*/
public enum TestRoute {
TEST1,
TEST2;
}
3、接口类
/**
* 接口类
* @date 2023/10/18 14:02
* @author luohao
*/
public interface TestService {
/**
* 返回参数
* @return
*/
String value();
}
4、实现类A
import org.springframework.stereotype.Service;
/**
* 实现类A
* @date 2023/10/18 14:01
* @author luohao
*/
@Service("TEST1")
public class TestAServiceImpl implements TestService{
@Override
public String value() {
return "吃饭";
}
}
5、实现类B
import org.springframework.stereotype.Service;
/**
* 实现类B
* @date 2023/10/18 14:01
* @author luohao
*/
@Service("TEST2")
public class TestBServiceImpl implements TestService{
@Override
public String value() {
return "睡觉";
}
}