Java.agency modelis a common design pattern used to provide a proxy for an object to control access to that object. According to the way the proxy class is implemented, it can be divided into static proxy and dynamic proxy. The following will introduce each of these two ways and analyze them in comparison.
static proxy
static proxyIt means that the implementation of the proxy class is determined at compile time. The proxy class needs to implement the same interface as the target object and hold a reference to the target object, through which the methods of the target object are invoked.
Implementation steps for static proxies
- Define the interface.
- Write the implementation class (target class) of the interface.
- Write a proxy class that implements the interface and holds a reference to the target class.
- In the proxy class, the actual method is called via a reference to the target class.
sample code (computing)
// Define the interface
public interface Hello {
void morning(String name);
}
// target class
public class HelloWorld implements Hello {
@Override
public void morning(String name) {
("Good morning, " + name);
}
}
// agent class
public class HelloProxy implements Hello {
// Internally maintains an attribute field for the target proxy object
private Hello target;
public HelloProxy(Hello target) {
= target;
}
@Override
public void morning(String name) {
("Before method invoke...");
(name); // 调用target class方法
("After method invoke...");
}
}
// Testing static proxies
public class Main {
public static void main(String[] args) {
Hello target = new HelloWorld(); // Creating Target Objects
Hello proxy = new HelloProxy(target); // Creating Proxy Objects
("Bob"); // Calling Proxy Methods
}
}
Output:
Before method invoke...
Good morning, Bob
After method invoke...
vantage
- The structure is simple and easy to understand.
- The proxy class can extend the functionality of the target class (e.g., add logging, permission checking, etc.).
drawbacks
- Every time you add an interface, you need to write a separate proxy class, which is poorly extensible.
- The agent class has a high maintenance workload.
dynamic agent
dynamic agentIt means that the proxy class is dynamically generated at runtime without defining the implementation class in advance. Its implementation relies heavily on Java'scap (a poem)
InvocationHandler
。
Dynamic Agent Implementation Steps
- Define the interface.
- establish
InvocationHandler
An implementation class of an interface to handle method calls. - utilization
()
Generate dynamic proxy objects.
sample code (computing)
import ;
import ;
import ;
// Define the interface
public interface Hello {
void morning(String name);
}
// Testing Dynamic Agents
public class Main {
public static void main(String[] args) {
// establishInvocationHandler
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
("Before method invoke...");
if (().equals("morning")) {
("Good morning, " + args[0]);
}
("After method invoke...");
return null;
}
};
// establish动态代理对象
Hello hello = (Hello) (
(), // class loader
new Class[] { }, // interface to be implemented
handler // method invocation handler
);
// Calling Proxy Methods
("Bob");
}
}
exports
Before method invoke...
Good morning, Bob
After method invoke...
The core of dynamic agents:
- InvocationHandlerInterface: defines the core of the agent logic.
- (): Responsible for dynamically generating proxy classes and returning proxy instances at runtime.
Dynamic proxying is essentially where the JVM generates the bytecode of the proxy class at runtime and loads it into memory.
Static vs. Dynamic Proxies
specificities | static proxy | dynamic agent |
---|---|---|
Proxy class implementation | Compile-time definition of proxy classes | Dynamic generation of proxy classes at runtime |
Support for interfaces | Each interface requires a separate implementation of the proxy class | It can be generalized and only needs to be implementedInvocationHandler
|
Code Extensibility | Low, add proxy class when adding new interfaces | High, just change the proxy logic |
performance overhead | Higher performance without reflection | Dependent on reflection calls, slightly lower performance |
application scenario | Small projects or interface stabilization scenarios | Scenarios for large projects, dynamically expanding functionality |
summarize
- static proxyIdeal for small projects, or scenarios where the agent class is relatively fixed.
- dynamic agentIdeal for scenarios where you need to dynamically extend functionality or reduce duplicate code.
- Dynamic agents are more flexible, especially widely used in AOP (cutter-oriented programming) frameworks, such as dynamic proxies in the Spring Framework.
The power of dynamic proxies is that they decouple the proxy logic from the concrete implementation, making the code more flexible and maintainable while providing higher reusability.