vendredi 29 janvier 2021

Design Pattern to use for populating object data across several services

I have a Car object that has several properties. Each of its properties are populated using a service (generally one property per service). Each of those services generally call a 3rd party web service (e.g. carClient) to get its data. Most of my services also have logic on how to populate its Car object field. For example:

@Service
@RequiredArgsConstructor
public class CarPriceService  {

    // client of a 3rd party web service interface
    // I don't have control over this interface.
    private final CarClient carClient;   
    
    public void setAutoPrice(Set<Car> cars) {  
        
        // in this case, only one call to the web service
        // is needed. In some cases, I need to make two calls
        // to get the data needed to set a Car property.
        Map<String, BigDecimal> carPriceById = 
                carClient.getCarPrice(cars.stream().map(c->c.getId()).collect(Collector.toSet()));
                
        for (Car car : cars) {            
            // in this case the poulating logic is simple
            // but for other properties it's more complex
            BigDecimal autoPrice = autoPriceById.get(car.getId());          
            car.setAutoPrice(autoPrice);
        }
    }
    
}

The order of populating the Car properties is sometimes important. For example, CarValueService sets car.value using car.condition which is set by CarConditionService.

Is there a design pattern that works for handling the gradual build of an object over services? I'm aware of the Builder pattern but not sure how it would apply here.

Aucun commentaire:

Enregistrer un commentaire