The Java proxy mode is divided into static agent and dynamic proxy mode
Static proxy mode is simpler, direct and code:
The proxy mode class diagram is as follows:
Roles in proxy mode:
Abstract Object role: declares a common interface between the target object and the proxy object, so that the proxy object can be used wherever the target object can be used.
target Object role: defines the target object that the proxy object represents.
proxy Object role: the proxy object contains a reference to the target object, so that the target object can be manipulated at any time, and the proxy object provides the same interface as the target object so that the target object can be substituted at any time. Proxy objects typically perform an operation before or after a client call is passed to the target object, rather than simply passing the call to the target object.
Source
Abstract Object Role
Package Proxy.staticproxy;
/**
* Interfaces to be implemented by abstract roles, real roles and proxy roles
* @author marcopan
*/
Public interface Iabstractsubject {
Proxy object and real role common method, rental ()
Public void Requesthouse ();
}
Target object Role
Package Proxy.staticproxy;
/**
* Real Character --landlord
* @author marcopan
*/
public class Realsubject implements Iabstractsubject {
@Override
Public void Requesthouse () {
System. out. println ("Requesthouse from Realsubject");
}
}
Proxy Object Role
Package proxy.staticproxy;
/**
* Proxy role, intermediary, reference with real role
* @author marcopan
*/
Public class Staticproxysubject implements Iabstractsubject {
References that contain real characters
Iabstractsubject subject = null;
Public Staticproxysubject () {
}
Public Staticproxysubject (Iabstractsubject subject) {
This . Subject = subject;
}
@Override
Public void Requesthouse () {
this.prerequest ();
subject.requesthouse ();
this.postrequest ();
}
Private void Prerequest () {
System. out. println ("Prerequest from Proxysubject");
}
Private void Postrequest () {
System. out. println ("Postrequest from Proxysubject");
}
}
Client
Package proxy.staticproxy;
Public class Client {
Public static void Main (string[] args) {
iabstractsubject subject = new Realsubject ();
iabstractsubject proxysubject = new Staticproxysubject (subject);
proxysubject.requesthouse ();
}
}
From the above example, you can see that the proxy object delegates the client's call to the target object, and can perform a specific operation before the method of the target object is called.
Java proxy mode