One, understand

Proxy, which provides a Proxy for other objects to control access to this object. From the naming of the schema, we can realize that the related operation should be performed by one class instead of another, similar to the meaning of the user. “You authorize me to use your function, and I can act on your behalf in this place.” It is worth noting that the function performed by the agent is actually the function of the function owner. Here is the proxy mode function diagram:

Why, one might ask, should I bother with a proxy class when I have access to all kinds of functionality? So this involves the application of the proxy mode. In fact, the application of the proxy mode is very extensive. It has roughly the following applications. First, remote proxies, which provide local representation of an object in different address Spaces, can hide the fact that an object exists in different address Spaces, such as you. If a Web application of.NET references a WebService, a WebReference file and folders are generated in the project. These folders are proxies so that the client can invoke the proxy to resolve the remote access problem. The second is the virtual proxy, which creates expensive objects as needed and uses it to store objects that take a long time to instantiate, so that performance can be optimized. The third is the security proxy, which is used to control the access permissions of real objects, generally used when objects have different access permissions. Fourth, there is intelligence guidance, which means that the proxy handles something else when the real object is called.

Second, the implementation

public abstract class Subject {
	public abstract void Request(a);
}
Copy the code
public class RealSubject extends Subject {

	@Override
	public void Request(a) {
		// Real demand operations}}Copy the code
public class Proxy extends Subject {
	RealSubject realSubject;

	@Override
	public void Request(a) {
		if(realSubject == null) {
			realSubject = newRealSubject(); } realSubject.Request(); }}Copy the code
public class Main {

	public static void main(String[] args) {
		Proxy proxy = newProxy(); proxy.Request(); }}Copy the code