design-patterns - 我应该使用工厂来更新对象吗?

标签 design-patterns domain-driven-design

我使用工厂通过命令对象创建实体,但是当我想从命令对象更新实体时,我找不到一个好的模式来做到这一点。我应该只使用工厂来更新实体,或者如果不是,什么是好的模式?

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::changeTitlePriduct::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/

相关文章:

domain-driven-design - 应用层是否应该依赖于 DDD 中的基础设施层?

c# - DDD 和 SOA 应用程序

domain-driven-design - CQRS 和 DDD 边界

c++ - 如何在 C++ 中透明地处理不同的协议(protocol)版本?

java - 以下结构是否被视为设计模式?

Scala - 如何避免对象工厂的 if/else 条件

c# - DDD : Lazy loading in aggregates

design-patterns - 红/黑部署和蓝/绿部署有什么区别?

security - 这种检查 "gift code"的方法安全吗?

domain-driven-design - DDD - 乐观并发属性(etag 或时间戳)是否应该成为域的一部分?