Proxy mode
The role of proxy mode is to provide a proxy for other objects to control access to this object.
In some cases, one customer does not want or cannot directly refer to another object, and the agent underground can act as an intermediary between the client and the target object.
The proxy mode typically involves three roles:
1. Abstract role: A common interface for declaring real objects and proxy objects;
2. Proxy role: The proxy object role contains a reference to the real object so that the real object can be manipulated, while the proxy object provides the same interface as the real object to replace the real object at any moment. At the same time, the proxy object can attach other actions when performing the real object operation, which is equivalent to encapsulating the real object;
3. Real role: The real object represented by the proxy role is the object we will eventually refer to.
Code implementation for 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 (); // Actions that are attached before a real-world role Operation if (Null == realsubject) { realsubject = new realsUbject (); } Realsubject.request (); //true character completion postrequest (); //actions attached after a real-world 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 (); }}
As can be seen from the above code, the customer actually needs to call the realsubject class request () method, now with proxysubject To proxy the realsubject class, it also achieves the purpose, and encapsulates other methods (prerequest (), Postrequest ()), which can handle some other problems.
If you want to use the proxy mode as described above, the real role must be pre-existing and used as the internal property of the proxy object. However, when used in practice, a real role must correspond to a proxy role, and if a large number of uses can cause a sharp expansion of the class, how do you use a proxy if you don't know the real role beforehand? This problem can be solved by the dynamic proxy class in Java.
Java record -90-static proxy mode depth profiling