Proxy mode

interface IService {
	public void execute();
}
class ServiceImpl implements IService {
	public ServiceImpl() {
		System.out.println("ServiceImpl is create");
	}
	@Override public void execute() {
		System.out.println("ServiceImpl.service is running......");
	}
}
public class Proxy implements IService {
	
	private IService service;
	
	public Proxy(IService service) {
		this.service = service;
	}
	
	@Override public void execute() {
		System.out.println("Proxy.service is calling ......");
		this.service.execute();
	}

	public static void main(String[] args) {

		IService proxy = new Proxy(new ServiceImpl());
		proxy.execute();
		
		IService virtualProxy = new VirtualProxy();
		virtualProxy.execute();
	}
}
//virtual proxy
class VirtualProxy implements IService {
	
	private IService service;
	public VirtualProxy() {}
	
	@Override public void execute() {
		System.out.println("VirtualProxy.service is calling ......");
		if (this.service == null)
			this.service = new ServiceImpl();
		this.service.execute();
	}
}

 The output is:

ServiceImpl is create
Proxy.service is calling ......
ServiceImpl.service is running......
VirtualProxy.service is calling ......
ServiceImpl is create
ServiceImpl.service is running......

 

 

 * Proxy mode: The proxy class and the business class implement the same business interface, and the proxy class holds the business class object through the constructor parameters.
   When the proxy class implements the business method, it calls the real business object method to implement the business logic, and can control the permissions in the business method

   And add aspect logic to implement proxying to business classes.
 
 * Intent: Provide a proxy for other objects to control access to this object. 
 
 * Remote Proxy (Remote Proxy) provides a local proxy object for an object located in a different address space.
 * Virtual Proxy (Virtual Proxy) creates expensive objects as needed. If you need to create an object that consumes a lot of resources,

   First create a relatively cheap object to represent, the real object will only be created when needed.
 * Protection Proxy (Protection Proxy) controls access to the original object. Protection proxies are used when objects should have different access rights.
 * Lazy loading, a classic application of lazy loading with proxy mode is in the Hibernate framework.
 * Pointer reference, which means that when the real object is called, the proxy does something else. For example, counting the number of references to real objects.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327016715&siteId=291194637