从另一个服务类调用服务方法

时间:2019-06-12 07:29:34

标签: java

我有两个服务类别。 WarehouseManagementService提供了管理仓库和库存的方法。 SalesManagementService提供了管理客户及其订单的方法。

要创建订单,必须检查订单项目数量是否足够。为此,我将使用WarehouseManagementService中的availableStock(Product p)方法。但我不知道如何正确调用此方法。

我是否必须在SalesManagementService中创建WarehouseManagementService的实例?还是应该将WarehouseManagementServiceInterface添加到SalesManagementService构造函数(依赖注入)?

一个好的架构看起来如何实现这两个类的松散耦合?

先谢谢了。

public class WarehouseManagementService implements WarehouseManagementServiceInterface {

    private DatabaseReadWarehouseInterface dbRead;
    private DatabaseWriteWarehouseInterface dbWrite;

    public int availableStock(Product p) {
    // returns available quantity of product
    }

}
public class SalesManagementService implements SalesManagementServiceInterface {

    private DatabaseReadSalesInterface dbRead;
    private DatabaseWriteSalesInterface dbWrite;

    public void addOrder(Order o) {
    // creates order, if product quantity is sufficient
    }

}

1 个答案:

答案 0 :(得分:3)

您有正确的感觉:应该注入依赖项。只要记住Single Responsibility Principle:“一堂课只有一个改变的理由”。

通过在WarehouseManagementService中构建SalesManagementService,您将添加SalesManagementService发生变化的第二个原因:当WarehouseManagementService的构建方式发生变化时。

要解决此问题,您可以使用成熟的Dependency Injection框架,也可以直接在SalesManagementService中添加构造函数参数开始:

public class SalesManagementService implements SalesManagementServiceInterface {

    private DatabaseReadSalesInterface dbRead;
    private DatabaseWriteSalesInterface dbWrite;
    private WarehouseManagementServiceInterface warehouseManagementService;

    constructor(DatabaseReadSalesInterface dbRead,
                DatabaseWriteSalesInterface dbWrite,
                WarehouseManagementServiceInterface warehouseManagementService) {
        this.dbRead = dbRead;
        this.dbWrite = dbWrite;
        this.warehouseManagementService = warehouseManagementService;
    }

    public void addOrder(Order o) {
    // creates order, if product quantity is sufficient
    }

}

然后在您的main方法中,注意实例化WarehouseManagementService并将其传递给SalesManagementService

作为旁注,您可能希望将SalesManagementServiceWarehouseManagementService的结构移入工厂,这些工厂为您提供SalesManagementServiceInterfaceWarehouseManagementServiceInterface而不是具体的类( “程序要接口,而不是实现”。