策略模式经典实战
/**
* 接口
*/
public interface ITestService {
public String sayHello();
}
//定义一个抽象,处理公共部分
public class AbstractTest {
public void commonHandler(){
System.out.println("AbstractTest#common");
}
}
/**
* 策略一
*/
@Service("aFaceServiceStrategyImpl")
public class ATestServiceStrategyImpl extends AbstractTest implements ITestService {
@Override
public String sayHello() {
commonHandler();
return "AFaceServiceImpl.sayHello()";
}
}
/**
* 策略二
*/
@Service("bFaceServiceStrategyImpl")
public class BTestServiceStrategyImpl extends AbstractTest implements ITestService {
@Override
public String sayHello() {
commonHandler();
return "BFaceServiceImpl.sayHello()";
}
}
/**
* 工厂类
* 通过入参type选择不同的策略执行
*/
@Component
public class ProcessFactroy implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {//此处特别注意,默认的入参是applicationContext,此处必须修改这个入参,比如改成arg0,否则启动项目会报错
applicationContext = arg0;
}
private static Map<String, ITestService> map = Maps.newHashMap();
@PostConstruct
public void register(){
map.put("a",applicationContext.getBean(ATestServiceStrategyImpl.class));
map.put("b",applicationContext.getBean(BTestServiceStrategyImpl.class));
}
public static ITestService getProcess(String type){
ITestService iTestService = map.get(type);
if(iTestService == null){
throw new RuntimeException("参数不合法");
}
return iTestService;
}
}
/**
* 控制层,通过ProcessFactroy 工厂选择不同策略执行
*/
@RestController
public class TestContoller {
@RequestMapping(value = "/test",method = RequestMethod.GET)
public String faceRecognition(@RequestParam("type") String type){
ITestService iTestService = ProcessFactroy.getProcess(type);
return iTestService.sayHello();
}
}