Video in progress

What is the Proxy pattern? What kinds are there?

A Proxy stands in for the real object and has the same interface, but does its own work before or after passing the call on: checking access, lazy loading, caching or a remote call.

📖 Answer

The client doesn't notice it's talking to a proxy. The kinds are named by their purpose:

  • Virtual proxy creates a heavy object only when it's really needed. Hibernate's lazy entities work this way.
  • Protection proxy checks permissions before the call.
  • Remote proxy makes a service behind the network look like a local object (an RMI stub, a Feign client).
  • Caching proxy remembers the result.
class CachingRateService implements RateService {
    private final RateService real;
    private final Map<String, BigDecimal> cache = new ConcurrentHashMap<>();

    CachingRateService(RateService real) { this.real = real; }

    public BigDecimal rate(String currency) {
        return cache.computeIfAbsent(currency, real::rate);
    }
}

In Spring, @Transactional, @Cacheable and @Async all work through proxies. So to understand Spring well, you have to know proxies.