Design pattern of proxy mode (static proxy)

Dynamic proxy detailed address The
proxy mode is also called the delegation mode. In layman's terms, there is an object acting as an agent for another object.
When it is difficult or not to directly access an object, it can be accessed indirectly through a proxy object. In order to be transparent to the caller. It is necessary to implement the same interface between the delegate object and the proxy object.
The proxy mode is divided into static proxy and dynamic proxy.

Static proxy is mainly: do not want to directly access an object, use a proxy class to access.
The static proxy mode is described in detail below.
There are many usage scenarios for static mode, and the general way of writing static proxy mode. The extraction interface is implemented separately from the proxy class and the proxy class. The proxy class is associated with the proxy class through the constructor. Then the method of the proxy class is called in the proxy class. To achieve the purpose of agency.
For example: now there is an interface CompanyInterface and Company and CompanyAgent.
A signContract method is now extracted from CompanyInterface. Use Company and CompanyAgent to implement this method respectively.

public interface CompanyInterface {
	//签订合同
	public void signContract(String company);

}

Company implementation class:

public class Company implements CompanyInterface {

	@Override
	public void signContract(String company) {
		System.out.println("我们和"+company+"签订合同了");
	}
}

CompanyAgent implementation class: An object that needs an agent is passed in through the construction method. In order to achieve decoupling with the Company. What we pass in here is the implementation class of CompanyInterface.


public class CompanyAgent implements CompanyInterface{

	private CompanyInterface companyImpl;
	public CompanyAgent(CompanyInterface companyImpl){
		this.companyImpl = companyImpl;
	}
	
	@Override
	public void signContract(String company) {
		System.out.println("我代表公司和"+company+"签订合同了");
		companyImpl.signContract(company);
	}

}

When calling: the method of the proxy class is called, in fact, the method of the proxy is called.

public class AgentMain {

	public static void main(String[] args) {
		Company tencent = new Company();
		CompanyAgent tencentAgent = new CompanyAgent(tencent);
		tencentAgent.signContract("阿里巴巴");
	}
}

Results of the:
Results of the

Guess you like

Origin blog.csdn.net/xu_coding/article/details/84076268