Junior — Middle
Explain the concept of proxy and in which scenarios it is used
sobes.tech AI
Answer from AI
A proxy is a surrogate object that controls access to another object. It implements the same interface as the original object and can add additional behavior when calling methods.
Use cases for proxies:
- Lazy loading: the object is created only upon first access.
- Access control: checking user permissions before method invocation.
- Logging and monitoring calls.
- Caching results.
- Transaction management.
For example, in Java, dynamic proxies can be used to add logging:
InvocationHandler handler = (proxy, method, args) -> {
System.out.println("Method call: " + method.getName());
return method.invoke(realObject, args);
};
MyInterface proxyInstance = (MyInterface) Proxy.newProxyInstance(
realObject.getClass().getClassLoader(),
realObject.getClass().getInterfaces(),
handler
);
Thus, proxies allow flexible extension of object behavior without changing their code.