Should I use factory to update an object?

I use factory to create an object from a command object, but when I want to update an object from a command object, I cannot find a good patten to do this. Should I just use factory to update the object or, if not, a good template?

interface ProductFactory {
    Product create(ProductCommand command);
    Product update(Product product, ProductCommand command);
}

my service:

class ProductServiceImpl {

     public Product updateProduct(long productId, ProductCommand command) {
         Product product = productRepository.findOne(productId);
         product = productFactory.update(product, productCommand);

         return productRepository.save(product);
     }
}
+4
source share
4 answers

In DDD, one of the strategic patterns is the use of the ubiquitous language in code. So, in your particular case, the class methods should be named according to what they do, for example, Product::changeTitleor 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 + Event sourcing, Application layer, command handler, , , Event store. .

+4

. A factory . , , ( ).

factory " ​​ " . , . - a factory, , , - . , .

: "", , UpdateService? , , .

+3

Domain Driven Design .

 public Product updateProduct(long productId, ProductCommand command) {
     Product product = productRepository.findOne(productId);

     product.update(productCommand);

     return productRepository.save(product);
 }
+1

, .

.

:

1) , .

2) Change the properties of the object you want with the values ​​that you get from the command. This is done by calling entity methods that update properties. You should not do this in a factory. factory is intended only to create an object. Changing an object is the behavior (method) proposed by the entity.

3) Call the repository to save the object.

0
source

Source: https://habr.com/ru/post/1681925/


All Articles