工厂模式+策略模式

UML:

工厂模式+策略模式_第1张图片

 class:

public interface IDeliveryService {

    /**
     * 创建第三方出货单
     * @param obj 入参
     */
    Object createThirdOrder(Object obj);
}
@Service
@RequiredArgsConstructor
public class DeliveryServiceImpl implements IDeliveryService {

    private final DeliveryStrategyFactory deliveryStrategyFactory;

    @Override
    public Object createThirdOrder(Object obj){
        // 根据type确定出库策略
        IDeliveryStrategy deliveryStrategy = deliveryStrategyFactory.getDeliveryStrategy(DeliveryPlatformEnum.MO_FANG);
        // 创建
        return deliveryStrategy.create((MoFangCreateOrderDTO )deliveryOrderDTO);
    }
}
@Component
public class DeliveryStrategyFactory implements ApplicationContextAware {

    private Map deliveryStrategyMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map beansOfType = applicationContext.getBeansOfType(IDeliveryStrategy.class);
        beansOfType.values().forEach(e-> deliveryStrategyMap.put(e.getDeliveryPlatformEnum(),e));
    }

    public IDeliveryStrategy getDeliveryStrategy(DeliveryPlatformEnum deliveryPlatformEnum){
        return deliveryStrategyMap.get(deliveryPlatformEnum);
    }
}
@Getter
public enum DeliveryPlatformEnum {
    /**
     * 魔方平台
     */
    MO_FANG(1,"魔方");

    private final Integer code;

    private final String description;

    DeliveryPlatformEnum(Integer code,String description) {
        this.code = code;
        this.description = description;
    }
}
public interface IDeliveryStrategy {
    /**
     * 策略所属平台枚举
     * @return 。
     */
    DeliveryPlatformEnum getDeliveryPlatformEnum();
    /**
     * 创建出货单
     * @param
     * @return
     */
    Object create(Object obj);
}
@Service
@RequiredArgsConstructor
public class MoFangDeliveryStrategy implements IDeliveryStrategy {

    private final MoFangClient moFangClient;

    @Override
    public DeliveryPlatformEnum getDeliveryPlatformEnum() {
        return DeliveryPlatformEnum.MO_FANG;
    }

    @Override
    public Object create(Object obj){
        return JsonUtils.toObject(moFangClient.createOrder((MoFangCreateOrderDTO) obj), MoFangCreateOrderResponse.class);
    }


}

你可能感兴趣的:(设计模式)