Java record-90-in-depth analysis of static proxy Mode
The proxy mode provides a proxy for other objects to control access to this object. In some cases, a customer does not want or cannot directly reference another object, and the agent can play a mediation role between the client and the target object. The proxy mode generally involves three roles: 1. abstract role: Declares the common interfaces of real objects and proxy objects. 2. proxy role: the proxy object role contains a reference to the real object to operate on the real object. At the same time, the proxy object provides the same interface as the real object to replace the real object at any time. At the same time, the proxy object can append other operations when performing real object operations, which is equivalent to encapsulating the real object; 3. real role: the real object represented by the proxy role is the object we finally want to reference. Code implementation in static proxy mode:
Public abstract class Subject {public abstract void request ();} public class RealSubject extends Subject {@ Override public void request () {System. out. println ("from real subject") ;}} public class ProxySubject extends Subject {private RealSubject realSubject; // The proxy role internally references the real role @ Override public void request () {preRequest (); // if (null = realSubject) {realSubject = new RealSubject ();} realSubject. request (); // postRequest () completed by the real role; // The operation attached after the real role operation} private void preRequest () {System. out. println ("pre request");} private void postRequest () {System. out. println ("post request") ;}} public class Client {public static void main (String [] args) {Subject subject = new ProxySubject (); subject. request ();}}
From the above code, we can see that the customer actually needs to call the request () method of the RealSubject class, And now uses ProxySubject to proxy the RealSubject class, which achieves the same purpose, other methods (preRequest () and postRequest () are encapsulated to handle other problems. If you want to use the proxy mode according to the above method, the real role must exist beforehand and use it as the internal attribute of the proxy object. However, in actual use, a real role must correspond to a proxy role. If a large number of roles are used, the class will expand sharply. In addition, if you do not know the real role, how can you use the proxy? This problem can be solved through the dynamic proxy class of Java.