1. Overview

In this tutorial, we'll examine the use cases of the Proxy Pattern and how we can implement it in Java.

2. When To Use

A proxy is a surrogate or placeholder for another object and controls access to it.

There are several cases where we can use the Proxy Pattern.

Firstly, we can create a proxy when we need to initialize an object on demand since it is expensive to create.

Moreover, we can use them when we must control access to the wrapped object.

Proxies are also useful when we want to cache the instances.

3. How to Implement

Generally, we start with an interface and an implementation. The proxy class also implements the interface and holds a reference to the implementation object. As a result, the proxy manages and forwards the method calls to the backing object.

Let's investigate the case where the target object is expensive to create.

public interface ExpensiveService {

    void create();
}

As the first step, we have the ExpensiveService interface.

public class ExpensiveServiceImpl implements ExpensiveService {

    // Expensive initialization
    public ExpensiveServiceImpl() {
        System.out.println("Expensive initialization process.");
    }

    @Override
    public void create() {
        System.out.println("Creating");
    }
}

Then we have an implementation of ExpensiveService. We assume that the construction phase is too expensive and we want to postpone it until needed.

As the last step, the proxy class implements the same interface, ExpensiveService. It'll create an ExpensiveServiceImpl instance when the create method is first called. Thus the construction will be lazy.

public class LazyLoadingServiceProxy implements ExpensiveService {

    @Override
    public void create() {
        ValueHolder.INSTANCE.create();
    }

    private static class ValueHolder {

        static final ExpensiveService INSTANCE = new ExpensiveServiceImpl();
    }
}

As we can see here, when LazyLoadingServiceProxy is created, it doesn't create the ExpensiveServiceImpl instance right away.

4. Summary

In this tutorial, we've examined the usage of Proxy Pattern in Java.

Finally, check out the source code for all examples over on Github.