我有两个服务班级。 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
}
}
最佳答案
您有正确的感觉:应该注入依赖项。只要记住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
。附带说明,您可能希望将
SalesManagementService
和WarehouseManagementService
的结构移入工厂,这些工厂为您提供SalesManagementServiceInterface
和WarehouseManagementServiceInterface
而不是具体的类(“程序接口,而不是实现”)。关于java - 从另一个服务类调用服务方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56556782/