Proxy object in Java

Posted by harsha on Mon, 16 Dec 2019 16:40:47 +0100

Static agent

Static agents are usually used to expand the original business logic, and achieve scalability by encapsulating real objects.

Three elements:

Common interface

public interface Action{
    void doSomething();
}

Real object

public class RealObject implements Action{
    
    public void doSomething(){
        System.out.println("do somethings");
    }
}

Proxy object

public class Proxy implements Action{
    private Action action;
    public Proxy(){
        this.action = RealObject()
    }
    
    public void doSomething() {
        System.out.println("proxy do");
        realObject.doSomething();
    }
}

Dynamic agent

Basic usage:

public class DynamicProxyHandler implements InvocationHandler {
    private Object realObject;

    public DynamicProxyHandler(Object realObject) {
        this.realObject = realObject;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //Agent extension logic
        System.out.println("proxy do");

        return method.invoke(realObject, args);
    }
}
public static void main(String[] args) {
        RealObject realObject = new RealObject();
        Action proxy = (Action) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{Action.class}, new DynamicProxyHandler(realObject));
        proxy.doSomething();
}

Comparison between static agent class and decorator model

  • What static proxy classes have in common with decorators:

(1) implement the same business interface as the target class

(2) declare the target object in both classes

(3) the target method can be enhanced without modifying the target class

  • The difference between static agent class and decorator:

    (1) for different purposes, decorators, in short, enhance the target object; static agents are used to protect and hide the target object
    (2) there are different ways to acquire the target object: the acquisition of the target object in the decorator is passed in by the proxy constructor. In the static proxy class, it is directly created in the nonparametric constructor.
    (3) in different decorator design patterns, there are decorator base classes, which can not be enhanced, but enhanced by specific decorators, so there is a "decorator chain"; in static agent, there is generally no parent-child relationship, and specific enhancement is realized by agent class. No subclass is needed, so there is no concept of chain.