Proxy

Definition


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

UML class diagram


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 for the real subject.
    • controls access to the real subject and may be responsible for creating and deleting it.
  • 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.

Sample code in Java

package com.hong.proxy;

interface Subject{
    public void request();
}

class RealSubject implements Subject{
    
    @Override
    public void request()
    {
        System.out.println("Request from RealSubject class");
    }
}

class Proxy implements Subject{ 
    
    private RealSubject realSubject;
    
    public Proxy()
    {
        realSubject = new RealSubject();
    }

    @Override
    public void request() {
        // TODO Auto-generated method stub
        System.out.println("Proxy additional operations before request"); 
        realSubject.request(); 
        System.out.println("Proxy additional operations after request");    
    } 

}

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

}