我使用工厂通过命令对象创建实体,但是当我想从命令对象更新实体时,我找不到一个好的模式来做到这一点。我应该只使用工厂来更新实体,或者如果不是,什么是好的模式?
interface ProductFactory {
Product create(ProductCommand command);
Product update(Product product, ProductCommand command);
}
我的服务:
class ProductServiceImpl {
public Product updateProduct(long productId, ProductCommand command) {
Product product = productRepository.findOne(productId);
product = productFactory.update(product, productCommand);
return productRepository.save(product);
}
}
最佳答案
在 DDD 上,战略模式之一是在代码中使用无处不在的语言。因此,在您的特定情况下,类方法应该根据它们的作用命名,例如 Product::changeTitle
或 Priduct::changePrice
:
此外,还有多种建筑风格。其中之一是没有命令对象但有多个参数,如下所示:
class ProductService {
public void changeProductPrice(long productId, double newPrice) {
Product product = productRepository.findOne(productId);
product.changePrice(product, newPrice);
productRepository.save(product);
}
}
这种风格遵循了很多无处不在的语言。
另一种风格是带有命令对象参数:
class ProductCommandHandler {
public void handleChangeProductPrice(ChangeProductPrice command) {
Product product = productRepository.findOne(command.getAggregateId ());
product.handleChangeProductPrice(command);
productRepository.save(product);
}
}
第二种风格非常适合 CQRS+事件源,您几乎可以消除
Application layer
通过提取泛型 command handler
从存储库中识别和加载聚合,它向它发送命令,它收集事件然后将它们持久化到 Event store
.我经常使用这种风格。
关于design-patterns - 我应该使用工厂来更新对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45228292/