DEV Community

eidher
eidher

Posted on • Edited on

2

Proxy Pattern

Provide a surrogate or placeholder for another object to control access to it.

Alt Text

Participants

  • Proxy: maintains a reference that lets the proxy access the real subject. Proxy may refer to a Subject if the RealSubject and Subject interfaces are the same. Provides an interface identical to Subject's so that a proxy can be substituted for the real subject. Controls access to the real subject and may be responsible for creating and deleting it. Other responsibilities depend on the kind of proxy: Remote proxies are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space. Virtual proxies may cache additional information about the real subject so that they can postpone accessing it. For example, the ImageProxy from the Motivation caches the real images' extent. Protection proxies check that the caller has the access permissions required to perform a request.
  • Subject: defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.
  • RealSubject: defines the real object that the proxy represents.

Code

public class Main {

    public static void main(String[] args) {
        Proxy proxy = new Proxy();
        proxy.request();
    }
}

public interface Subject {
    void request();
}

public class RealSubject implements Subject {

    @Override
    public void request() {
        System.out.println("Called RealSubject.Request()");
    }
}

public class Proxy implements Subject {

    private RealSubject realSubject;

    @Override
    public void request() {
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        realSubject.request();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Called RealSubject.Request()
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay