我有两个服务类别。 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
}
}
答案 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
。
作为旁注,您可能希望将SalesManagementService
和WarehouseManagementService
的结构移入工厂,这些工厂为您提供SalesManagementServiceInterface
和WarehouseManagementServiceInterface
而不是具体的类( “程序要接口,而不是实现”。