在电商项目中,会存在不同类型的订单。不同类型订单的创建实现策略不同,下面我们介绍一下基于策略模式来实现不同类型的订单创建流程。
假设,我们现在需要基于不同的业务需求需要创建普通订单和虚拟订单,首先定义如下订单创建策略接口 createOrder:
1 2 3 4 5 6
|
public interface CreateOrderService { CreateOrderResponse createOrder(CreateOrderRequest createOrderRequest); }
|
不同类型的订单创建策略不同,下面定义普通订单和虚拟订单类,分别实现接口 CreateOrderService:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class BeanIdsConstant { public static final String CREATE_NORMAL_ORDER_SERVICE = "createNormalOrderServiceImpl"; public static final String CREATE_VIRTUAL_ORDER_SERVICE = "createVirtualOrderServiceImpl"; }
@Service(BeanIdsConstant.CREATE_NORMAL_ORDER_SERVICE) public class CreateNormalOrderServiceImpl implements CreateOrderService { @Override public CreateOrderResponse createOrder(CreateOrderRequest createOrderRequest) { System.out.println("start create normal order"); return null; } }
@Service(BeanIdsConstant.CREATE_VIRTUAL_ORDER_SERVICE) public class CreateVirtualOrderServiceImpl implements CreateOrderService { @Override public CreateOrderResponse createOrder(CreateOrderRequest createOrderRequest) { System.out.println("start create virtual order"); return null; } }
|
接着我们创建一个策略工厂,负责 CreateNormalOrderServiceImpl 和 CreateVirtualOrderServiceImpl 的实例创建获取(实际创建过程我们这里直接交由 Spring 处理,我们只需要从 IOC 容器获取即可),具体如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
public interface CreateOrderServiceFactory { CreateOrderService getCreateOrderService(OrderTypeEnum orderTypeEnum); }
@Configuration public class OrderServiceConfiguration {
@Bean public Properties serviceMappings() { Properties properties = new Properties(); properties.setProperty(OrderTypeEnum.NORMAL.name(), BeanIdsConstant.CREATE_NORMAL_ORDER_SERVICE); properties.setProperty(OrderTypeEnum.VIRTUAL.name(), BeanIdsConstant.CREATE_VIRTUAL_ORDER_SERVICE); return properties; }
@Bean public FactoryBean<Object> orderServiceFactoryBean(Properties serviceMappings) { ServiceLocatorFactoryBean factoryBean = new ServiceLocatorFactoryBean(); factoryBean.setServiceLocatorInterface(CreateOrderServiceFactory.class); factoryBean.setServiceMappings(serviceMappings); return factoryBean; } }
|
如下,我们就能够实现普通订单的创建:
1 2 3 4 5
| @Test public void createOrder() { CreateOrderRequest createOrderRequest = new CreateOrderRequest(); createOrderServiceFactory.getCreateOrderService(OrderTypeEnum.NORMAL).createOrder(createOrderRequest); }
|