Static proxy and dynamic proxy, static proxy dynamic proxy

Source: Internet
Author: User

Static proxy and dynamic proxy, static proxy dynamic proxy

The so-called proxy Design refers to the operation of a real subject by a proxy subject, and the actual subject executes specific business operations, while the proxy subject is responsible for the processing of other related businesses.

This is often the case in the system: verification is required before some operations, such as advanced user information verification when adding or deleting operations, to check whether the user has permissions for these operations. The Code is as follows:

// UserManager interface: public interface UserManager {public void addUser (String username, String password); public void delUser (int userId);} // UserManagerImpl class to implement the UserManager interface: public class UserManagerImpl implements UserManager {public void addUser (String username, String password) {checkSecurity (); System. out. println ("--------- UserManagerImpl. add () -------- ");} public void delUser (int userId) {checkSecurity (); System. out. println ("--------- UserManagerImpl. delUser () -------- ");} private void checkSecurity () {System. out. println ("------- checkSecurity -------");}}

When the verification function checkSecurity () is added to the Add/delete method, the problem arises. If the verification function checkSecurity () needs to be added to hundreds of functions, hundreds of checkSecurity () are required () function. If the requirement changes one day and user verification is not required, you need to delete checkSecurity () from hundreds of functions, resulting in poor maintainability. How can this problem be solved?

1. Static proxy

Add proxy class

Public class UserManagerImpl implements UserManager {public void addUser (String username, String password) {// checkSecurity (); System. out. println ("--------- UserManagerImpl. add () -------- ");} public void delUser (int userId) {// checkSecurity (); System. out. println ("--------- UserManagerImpl. delUser () -------- ");} // private void checkSecurity () {// System. out. println ("------- checkSecurity -------"); //} // UserManagerImplProxy proxy class: (Note: This proxy class can only serve UserManager APIs) public class UserManagerImplProxy implements UserManager {private UserManager userManager; public UserManagerImplProxy (UserManager userManager) {this. userManager = userManager;} public void addUser (String username, String password) {checkSecurity (); userManager. addUser (username, password);} public void delUser (int userId) {checkSecurity (); userManager. delUser (userId);} private void checkSecurity () {System. out. println ("------- checkSecurity -------");}}

Static Proxy:

Proxy class -- created during compilation, UserManagerImplProxy can only serve the UserManager interface;


Adding or deleting a proxy class ensures that the target function is not changed and the maintainability is enhanced. However, the root problem is not solved because the problem is transferred to the proxy class, the problems mentioned above still exist. How can this problem be solved?

2. Dynamic Proxy:

Take out a total of checkSecurity () Verification and place it in a separate class;

Proxy class-created at runtime, which can serve each interface;

Dynamic proxy considerations: place independent services (cross-cutting services) distributed in the system in one place and automatically place them at runtime. Horizontal issues are considered;

Code:

// UserManager interface public interface UserManager {public void addUser (String username, String password); public void delUser (int userId );} // UserManagerImpl class implements the UserManager interface public class UserManagerImpl implements UserManager {public void addUser (String username, String password) {// checkSecurity (); System. out. println ("--------- UserManagerImpl. add () -------- ");} public void delUser (int userId) {// checkSecurity (); System. out. println ("--------- UserManagerImpl. delUser () -------- ");} // private void checkSecurity () {// System. out. println ("------- checkSecurity -------"); //} import java. lang. reflect. invocationHandler; import java. lang. reflect. method; import java. lang. reflect. proxy; // The interface InvocationHandlerpublic class SecurityHandler implements InvocationHandler {private Object targetObject; // target class, create Proxy class based on the target // create Proxy class public Object createProxyInstance (Object targetObject) export this.tar getObject = targetObject; // generate Proxy based on the target // parameter: 1st parameters: Agent class loading Proxy class; 2nd parameters: Target Interface; 3rd parameters: return Proxy. newProxyInstance (targetObject. getClass (). getClassLoader (), targetObject. getClass (). getInterfaces (), this);} public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {checkSecurity (); // call the target method Object ret = Method. invoke (targetObject, args); return ret;} private void checkSecurity () {System. out. println ("------- checkSecurity -------") ;}// Client public class Client {public static void main (String [] args) {SecurityHandler hander = new SecurityHandler (); // generate the proxy UserManager userManager = (UserManager) hander. createProxyInstance (new UserManagerImpl (); userManager. addUser ("zhangsan", "123"); // call the ddUser () method }}


3. Summary

Static proxy usually only acts as a proxy for one class. Dynamic proxy is used to represent multiple implementation classes under an interface.
The static proxy knows in advance what the proxy is, but the dynamic proxy does not know what the proxy is, and it is only known at runtime.
Dynamic proxy is the invoke method that implements the InvocationHandler interface in JDK, but note that the proxy is an interface, that is, your service class must implement the interface, obtain the Proxy object through newProxyInstance in Proxy.
There is also a dynamic proxy CGLIB. The proxy is a class, and the business class inheritance interface is not required. The derived subclass is used to implement the proxy. You can modify the class by dynamically modifying the bytecode at runtime.



What are the definitions of dynamic and static proxies in Java?

Comparison between static and dynamic proxies in JAVA
I. Concepts
The proxy mode is a common Java design mode. It features the same interface between the proxy class and the delegate class. The proxy class is mainly responsible for preprocessing, filtering, and forwarding messages to the delegate class, and post-processing messages. There is usually an association between the proxy class and the delegate class. A proxy class object is associated with a delegate class object. The proxy class object itself does not actually implement the service, but calls the relevant methods of the delegate class object, to provide specific services. According to the creation period of the proxy class, the proxy class can be divided into two types.

Static proxy class:
The source code is automatically generated by the programmer or by a specific tool, and then compiled. Before running the program, the. class file of the proxy class already exists. Dynamic Proxy: dynamically created by using the reflection mechanism when the program is running.

Ii. Static proxy
As follows, the HelloServiceProxy class is the proxy class, And the HelloServiceImpl class is the delegate class, both of which implement the HelloService interface. The HelloServiceImpl class is the real implementer of the HelloService interface, and the HelloServiceProxy class provides specific services by calling the methods of the HelloServiceImpl class. The echo () method and getTime () method of the HelloServiceProxy class call the echo () method and getTime () method of the HelloServiceImpl object to be proxy respectively, some simple printing operations will be performed before and after the method call.

It can be seen that the proxy class can pre-process messages for the delegate class, forward messages to the delegate class, and post-process messages.

Routine 1 HelloService. java
Package proxy;
Import java. util. Date;
Public interface HelloService {
Public String echo (String msg );
Public Date getTime ();
}
Routine 2 HelloServiceImpl. java
Package proxy;
Import java. util. Date;
Public class HelloServiceImpl implements HelloService {
Public String echo (String msg ){
Return "echo:" + msg;
}
Public Date getTime (){
Return new Date ();
}
}
Example 3 HelloServiceProxy. java
Package proxy;
Import java. util. Date;
Public class HelloServiceProxy implements HelloService {
Private HelloService helloService; // indicates the HelloService instance to be proxy
Public HelloServiceProxy (HelloService helloService ){
This. helloService = helloService;
}
Public void setHelloServiceProxy (HelloService helloService ){
This. helloService = helloService;
}
Public String echo (String msg ){
System. out. println (&... the remaining full text>

Whether the proxy in Spring is dynamic or static

There are two main proxy modes: static proxy and dynamic proxy.

1. Static Proxy:

For example, to print a string "Welcome" before "HelloWorld" is output"

A: First define an interface class.

Public interface HelloWorldIF {
Public void print ();
// Public void say ();
}

B: Define an implementation class for this interface.

Public class HelloWorldImpl implements HelloWorldIF {

Public void print (){
System. out. println ("HelloWorld ");
}
// Public void say (){
// System. out. println ("Say Hello! ");
//}
}

C: Define a static proxy class

Public class StaticProxy implements HelloWorldIF {

Public HelloWorld helloWorld;
Public StaticProxy (HelloWorld helloWorld ){
This. helloWorld = helloWorld;
}

Public void print (){
System. out. println ("Welcome ");
// Equivalent to callback
HelloWorld. print ();
}

// Public void say (){
//// Equivalent to callback
// HelloWorld. say ();
//}
}

It can be seen that the static proxy class has a very unpleasant disadvantage: if you add a method to the interface (comment out all the code above ), all implementation classes and proxies need to be implemented. This increases the complexity of the Code. Dynamic proxy can avoid this disadvantage.

2. Dynamic proxy

The biggest advantage of dynamic proxy compared with normal proxy is that all methods declared in the interface are transferred to a centralized method for processing (invoke, when there are a large number of interface methods, we can flexibly process them without requiring each method to Be Transited like a static proxy.

The dynamic proxy class can only be a proxy interface, and the proxy class must implement the InvocationHandler class to implement the invoke method. This method is called when calling all the methods of the proxy interface, and the value returned by the invoke method is an implementation class of the proxy interface.

Proxy type:

Import java. lang. reflect. InvocationHandler;
Import java. lang. reflect. Method;
Import java. lang. reflect. Proxy;
// The dynamic proxy class can only be a proxy interface, and the proxy class must implement the InvocationHandler class to implement ...... the remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.