适配器的应用(泛型模式)

适配器模式是一种重要的设计模式,能让代码简练。直接上代码。
定义接口,如下所示:

public interface IOrderOperate<C, U, D> {

    /**
     * 创建单据
     */
    boolean creatOrder(C param);

    /**
     * 批量创建
     * @param param
     * @return
     */
    boolean batchCreateOrder(C param);

    /**
     * 修改单据
     */
    boolean updateOrder(U param);

    /**
     * 删除单据
     */
    boolean deleteOrder(D param);


}

定义抽象类如下所示:主要是在抽象类中完成保存,修改调用第三方接口实现的逻辑。

@Component
@Slf4j
public abstract class AbstractOperate<C, U, D> implements IOrderOperate<C, U, D> {

    @Autowired
    private SalesRepo salesRepo;


    protected abstract SaveDTO convertCreate(C param);

    protected abstract List<UpdateDTO> convertUpdate(U param);

    protected abstract DelDTO convertDelete(D param);

    @Override
    public boolean creatOrder(C param) {
        SaveDTO createParam = convertCreate(param);
        return salesRepo.saveSalesUnInvoice(createParam);
    }

    @Override
    public boolean updateOrder(U param) {
        List<UpdateDTO> updateParams = convertUpdate(param);
        return salesRepo.updateSalesUnInvoice(updateParams);
    }

    @Override
    public boolean deleteOrder(D param) {
        DelDTO deleteParam = convertDelete(param);
        return salesRepo.deleteUnInvoiceBySalesOrderId(deleteParam);
    }

}

定义适配器实现,完成参数转化,也就是目标的接口需要的参数。

@Component
@Slf4j
public class SalesInvoiceAdapter extends
        AbstractOperate<SalesRefundOrderCreateMessageDto, SalesRefundOrderUpdateMessageDto, SalesRefundOrderDeleteMessageDto> {


    @Autowired
    private SalesRefundRepo salesRefundRepo;

    @Override
    protected SaveDTO convertCreate(SalesRefundOrderCreateMessageDto param) {
        SalesRefundOrderDetailDto salesRefundOrderDetailDto = salesRefundRepo.getById(param.getId());
        SaveSalesUnInvoiceDTO createParam = new SaveSalesUnInvoiceDTO();return createParam;
    }

    @Override
    protected List<UpdateDTO> convertUpdate(SalesRefundOrderUpdateMessageDto param) {
        SalesRefundOrderDetailDto salesRefundOrderDetailDto = salesRefundRepo.getById(param.getId());
        UpdateSalesDTO updateParam = new UpdateSalesDTO();return Arrays.asList(updateParam);
    }

    @Override
    protected DelDTO convertDelete(SalesRefundOrderDeleteMessageDto param) {
        List<SalesRefundOrderDO> salesRefundOrderDOList = salesRefundRepo.getByIds(param.getIds());
        DelUnInvoiceBySalesIdDTO deleteParam = new DelUnInvoiceBySalesIdDTO();return deleteParam;
    }

 
}

调用实现代码如下所示:调用适配器的操作逻辑方法即可。

  public static void main(String[] args) {
        salesAdapter.updateOrder(salesMessageDto);
    } 

总结:适配器设计模式是一种很常见的设计模式。

 

posted @ 2022-08-19 16:40  郭慕荣  阅读(89)  评论(0编辑  收藏  举报