Skip to the content.
package com.bookshop.solid.dip;

import com.bookshop.domain.Book;
import com.bookshop.domain.Customer;
import java.math.BigDecimal;
import java.util.List;

/**
 * High-level policy: what it means to place an order. Depends only on the two
 * abstractions -- it cannot name, and so cannot be coupled to, any concrete
 * gateway or database.
 */
public class OrderService {

    private final PaymentGateway payments;
    private final OrderRepository orders;

    public OrderService(PaymentGateway payments, OrderRepository orders) {
        this.payments = payments;
        this.orders = orders;
    }

    public PlacedOrder placeOrder(Customer customer, List<Book> books) {
        BigDecimal total = books.stream().map(Book::price).reduce(BigDecimal.ZERO, BigDecimal::add);
        String paymentRef = payments.charge(customer, total);
        PlacedOrder order = new PlacedOrder(customer.id(), total, paymentRef);
        orders.save(order);
        return order;
    }
}

Raw file