- 策略接口
/** * @author micky * @date 2021/11/19 * 策略接口 */ public interface DeviceRegisterStrategy { Object callIoDevice(xxxx); }
- 定义策略实现类
@Component public class FirstRegStrategy implements DeviceRegisterStrategy { @Override public Object callIoDevice(xxxxx){ doSomeThing(); //自定义策略逻辑 } }
@Component public class RecoverRegStrategy implements DeviceRegisterStrategy { @Override public Object callIoDevice(xxxx) { doSomeThing(); // 自定义策略逻辑 } }
- 工厂类
/** * @author micky * @since 2021/11/19 */ @Component public class DeviceRegisterStrategyFactory { private static final Map<String, DeviceRegisterStrategy> map = new HashMap<>(2); @Autowired private FirstRegStrategy firstRegStrategy; @Autowired private RecoverRegStrategy recoverRegStrategy; @PostConstruct public void initDeviceRegisterStrategy(){ map.put("FirstRegister",firstRegStrategy); map.put("RecoverRegister",recoverRegStrategy); } public static DeviceRegisterStrategy getDeviceRegisterStrategy(String name) { return map.get(name); } }
为了便于管理 ,name 也可以定义枚举类
package com.xhwl.smarthome.pojo.enums; /** * @author wangxinyu * * @date 2021/11/19 */ public enum RegisterEnum { FIRST_REG(1,"FirstRegister"), RECOVER_REG(2,"RecoverRegister"); private int type; private String name; public int getType() { return type; } public String getName() { return name; } RegisterEnum(int type, String name) { this.type = type; this.name = name; } RegisterEnum(){} public static RegisterEnum of(int type){ for (RegisterEnum e : RegisterEnum.values()) { if(e.getType() == type){ return e; } } return null; } }
- 测试
@Autowired private DeviceRegisterStrategyFactory strategyFactory; @PostMapping("/test") public void initializationInv(@RequestParam(value = "name") String name){ strategyFactory.getDeviceRegisterStrategy(name).callIoDevice(); }