1. 创建Springboot项目
2. 创建策略接口类
public interface TwoHandler { boolean accept(String type); void handler(); }
3. 创建具体策略类
@Service public class Handler1 implements TwoHandler{ @Override public boolean accept(String type) { return "handler1".equals(type); } @Override public void handler() { System.out.println("Handler1处理完成"); } }
@Service public class Handler2 implements TwoHandler{ @Override public boolean accept(String type) { return "handler2".equals(type); } @Override public void handler() { System.out.println("Handler2处理完成"); } }
4. 创建策略使用门面
@Component public class TwoContext { @Autowired private ListhandlerList; public void handle(String type){ TwoHandler handler = Optional.ofNullable(handlerList).orElseGet(null) .stream().filter(h -> h.accept(type)) .findFirst().orElse(null); if(handler == null){ throw new RuntimeException("can not find handler"); } handler.handler(); } }
5. 使用
@SpringBootTest class ApplicationTests { @Autowired private TwoContext twoContext; @Test void contextLoads() { twoContext.handle("handler1"); } }
输出
Handler1处理完成