1. 创建SpringBoot项目
2. 创建抽象类AbstractThreeHandler
public abstract class AbstractThreeHandler implements InitializingBean {
@Autowired
private HandlerContext handlerContext;
public abstract boolean accept(String type);
public abstract void handler();
@Override
public void afterPropertiesSet() throws Exception {
handlerContext.register(this);
}
}
3. 创建策略具体类
@Service
public class Handler31 extends AbstractThreeHandler {
@Override
public boolean accept(String type) {
return "handler31".equals(type);
}
@Override
public void handler() {
System.out.println(Handler31.class.getSimpleName()+"处理完成");
}
}
@Service
public class Handler32 extends AbstractThreeHandler {
@Override
public boolean accept(String type) {
return "handler32".equals(type);
}
@Override
public void handler() {
System.out.println(Handler32.class.getSimpleName()+"处理完成");
}
}
4. 创建获取策略类
@Component
public class HandlerContext{
private List<AbstractThreeHandler> handlers = new ArrayList<>();
void register(AbstractThreeHandler handler){
handlers.add(handler);
}
public AbstractThreeHandler getHandler(String type){
AbstractThreeHandler handler = handlers.stream()
.filter(h -> h.accept(type))
.findFirst()
.orElse(null);
if(handler == null){
throw new RuntimeException("can not find handler");
}
return handler;
}
}
5. 使用
private HandlerContext handlerContext;
@Test
void contextLoads() {
handlerContext.getHandler("handler32").handler();
}
结果:
Handler32处理完成