Skip to the content.
package com.bookshop.structural.proxy;

import com.bookshop.domain.Book;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * The proxy: same interface as the real catalog, but answers repeat lookups from a
 * local cache. Clients gain caching without changing a single line.
 */
public class CachingCatalogProxy implements BookCatalog {

    private final BookCatalog remote;
    private final Map<String, Optional<Book>> cache = new HashMap<>();

    public CachingCatalogProxy(BookCatalog remote) {
        this.remote = remote;
    }

    @Override
    public Optional<Book> findByIsbn(String isbn) {
        return cache.computeIfAbsent(isbn, remote::findByIsbn);
    }
}

Raw file