- 一、为什么要用到策略模式
- 二、代码实现
1.接口类
public interface CreateOrderService { CreateOrderDto createOrder(CreateOrderVm createOrderVm); }
2.多个接口实现类
@Service public class CreateAdvanceOrderImpl implements CreateOrderService { @Override public CreateOrderDto createOrder(CreateOrderVm createOrderVm) { System.out.println("创建先行订单"); return null; } }
@Service public class CreateReserveOrderImpl implements CreateOrderService { @Override public CreateOrderDto createOrder(CreateOrderVm createOrderVm) { System.out.println("创建预定订单"); return null; } }
@Service public class CreateOrderImpl implements CreateOrderService { @Override public CreateOrderDto createOrder(CreateOrderVm createOrderVm) { System.out.println("创建现货订单"); return null; } }
3.枚举类
public enum CreateOrderStrategyEnum { 先行(0, "com.gemo.bear.service.order.impl.CreateAdvanceOrderImpl"), 定金预定(3, "com.gemo.bear.service.order.impl.CreateReserveOrderImpl"), 现货(6, "com.gemo.bear.service.order.impl.CreateOrderImpl"); private Integer openStart; //状态 private String objectPath;//类的完全限定名:包名+类名 CreateOrderStrategyEnum(Integer openStart, String objectPath) { this.openStart = openStart; this.objectPath = objectPath; } public static String getCreateOrderObject(Integer openStart) { for (CreateOrderStrategyEnum value : CreateOrderStrategyEnum.values()) { if (openStart == value.openStart) { return value.objectPath; } } return null; } }
4.策略类
public class CreateOrderStrategy { private CreateOrderService createOrderService; public CreateOrderStrategy(CreateOrderService createOrderService) { this.createOrderService = createOrderService; } public CreateOrderDto createOrder(CreateOrderVm createOrderVm) { return this.createOrderService.createOrder(createOrderVm); } }
5.策略类的使用
@ApiOperation("订单创建") @PostMapping("create-order-test") public ResponseBuild createOrderTest(@Validated @RequestBody CreateOrderVm createOrderVm) { try { //类的完全限定名:包名+类名 String object = CreateOrderStrategyEnum.getCreateOrderObject(createOrderVm.getOpenState()); //调用无参构造器创建实例 CreateOrderService createOrderService = (CreateOrderService) Class.forName(object).newInstance(); CreateOrderStrategy createOrderStrategy = new CreateOrderStrategy(createOrderService); return ResponseBuild.success(createOrderStrategy.createOrder(createOrderVm)); } catch (Exception e) { e.printStackTrace(); } return null; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)