[Java project practice] Proxy Pattern, static Proxy VS dynamic Proxy, proxypattern

Source: Internet
Author: User

[Java project practice] Proxy Pattern, static Proxy VS dynamic Proxy, proxypattern


In this blog post, we will compare and learn static proxy and dynamic proxy in the form of class diagrams and code, focusing on analyzing their respective advantages and disadvantages.


Definition


Proxy Pattern is the structure mode of an object. Proxy Pattern provides a Proxy object for an object and controls the reference to the original object by the Proxy object.


Category


Static proxy and dynamic proxy


Static proxy


Static proxy class diagram



Sample Code



Interface

package com.liang.pattern;public interface UserManager {public void addUser(String userId,String userName);public void delUser(String userId);public void modifyUser(String userId,String userName);public String findUser(String userId);}

Target object

Package com. liang. pattern; public class UserManagerImpl implements UserManager {public void addUser (String userId, String userName) {try {System. out. println ("UserManagerImpl. addUser () userId --> "+ userId);} catch (Exception e) {e. printStackTrace (); throw new RuntimeException () ;}} public void delUser (String userId) {System. out. println ("UserManagerImpl. delUser () userId --> "+ userId);} public String findUser (String userId) {System. out. println ("UserManagerImpl. findUser () userId --> "+ userId); return" Yu Liang ";} public void modifyUser (String userId, String userName) {System. out. println ("UserManagerImpl. modifyUser () userId --> "+ userId );}}

Proxy object. We use the proxy object to make some log records. We print the simple information to the console.

Package com. liang. pattern; public class UserManagerImplProxy implements UserManager {private UserManager userManager; public UserManagerImplProxy (UserManager userManager) {this. userManager = userManager;} public void addUser (String userId, String userName) {// logs and other operations or print the input parameter System. out. println ("start --> addUser () userId -->" + userId); try {userManager. addUser (userId, userName); // The execution is successful, and the message System is printed successfully. out. println ("success --> addUser ()");} catch (Exception e) {e. printStackTrace (); // when the error occurs, print the failure information System. out. println ("error --> addUser ()"); // throw new RuntimeException () ;}} public void delUser (String userId) {// same as above, slightly userManager. delUser (userId);} public String findUser (String userId) {// same as above, slightly userManager. findUser (userId); return null;} public void modifyUser (String userId, String userName) {// same as above, slightly userManager. modifyUser (userId, userName );}}

Client call

Package com. liang. pattern; public class Client {/*** @ param args */public static void main (String [] args) {UserManager userManager = new UserManagerImplProxy (new UserManagerImpl (); userManager. addUser ("001", "Yu Liang ");}}

Output result. This method is successfully executed.

start-->>addUser() userId-->>001UserManagerImpl.addUser() userId-->>001success-->>addUser()

From the class diagram, we can see that the client can directly deal with the target object, and an indirect layer is added in the proxy. they implement the same functions without changing the parameters. I believe that you are familiar with the class diagrams and code above. It is no different from reading other blog posts. Let's take a look at the advantages and disadvantages of static proxy.


Advantages and disadvantages


Advantages:

1. Intuitive feeling: static proxy actually exists and we write it on our own.

2. When added during the compilation period, it is highly efficient to specify who calls the program in advance.


Disadvantages:

Similarly, its advantages have become its fatal disadvantages.

1. Static proxy is very troublesome and requires a large number of proxy classes

When we have multiple target objects that require proxy, we need to create multiple proxy classes and change the original code. If we change the code more often, the problem may occur. We need to retest it.

2. Repeated code may appear in every corner, violating the principle that repetition is not a good taste.

We should avoid repeated attempts.

3. added during compilation, resulting in poor system flexibility



Next let's take a look at the dynamic proxy.


Dynamic proxy


Dynamic proxy class diagram



Sample Code



Proxy class (do not understand, just look at the comment)

Package com. liang. pattern; import java. lang. reflect. invocationHandler; import java. lang. reflect. method; import java. lang. reflect. proxy;/*** the InvocationHandler interface must be implemented when JDK dynamic Proxy is used. The Proxy class is used to create the corresponding Proxy class * @ author liang **/public class ProxyHandler implements InvocationHandler {private Object targetObject; /*** proxy Initialization Method * @ param targetObject * @ return */public Object newProxyInstance (Object targetobject?#this.tar GetObject = targetObject; // The first parameter, the class loader of the target // The second parameter, the interface of the target object // The third parameter, calls the InvocationHandler object, once you call the Proxy, the Proxy will call the InvocationHandler's invoke method return Proxy. newProxyInstance (targetObject. getClass (). getClassLoader (), targetObject. getClass (). getInterfaces (), this);}/*** reflection, so that you can call a class method based on the configured parameters without knowing the specific class. It is useful in flexible programming. */Public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {// record logs and other operations or print the input parameter System. out. println ("start -->" + method. getName (); for (int I = 0; I <args. length; I ++) {// print the System parameter that calls the target method. out. println (args [I]);} Object ret = null; try {// call the target method ret = method. invoke (targetObject, args); // The execution is successful, and the message System is printed successfully. out. println ("success -->" + method. getName ();} catch (Exception e) {e. printStackTrace (); // when the error occurs, print the failure information System. out. println ("error -->" + method. getName (); throw e;} return ret ;}}

Client call

package com.liang.pattern;public class Client {/** * @param args */public static void main(String[] args) {ProxyHandler proxyHandler = new ProxyHandler();UserManager userManager = (UserManager)proxyHandler.newProxyInstance(new UserManagerImpl());String name = userManager.findUser("0001");System.out.println("client.main-->>" + name);}} 


Output result, run successfully

Start --> findUser0001UserManagerImpl. findUser () userId --> 0001success --> findUserclient. main --> Yu Liang


Interface and target class. Same as above, I will not waste everyone's bandwidth.


Advantages and disadvantages
Advantages:

1. A dynamic proxy class is simpler. It can solve the trouble of creating multiple static proxies and avoid repeated redundant code.

2. When calling the target code, it will dynamically Add the method "RunTime" to decide what type you are, who to call, and flexible


Disadvantages:

1. The system is flexible, but the efficiency is lower than that of static proxy.

2. Dynamic proxy is a little less readable than static proxy and is not easy to understand.

3. JDK dynamic proxy can only proxy classes that implement interfaces


Summary


Static proxy VS dynamic proxy, playing the same role, each has its own unique characteristics, can not be replaced, in the end in the project to use which proxy, there is no best, only more suitable.




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>

What is the java proxy mode? What is the specific dynamic proxy and static proxy? Better example

Class
{
Void a1 () {System. out. print ("");}
}

Class B
{
B ()
{
A aa = new ();
}
Void b1 ()
{
Aa. a1 ();
}
}
In the above example, a simple proxy mode is used to create an object of a in B, and then investigate the a1 method of a in the b1 method of B.
If you instantiate an object named B, calling the b1 method of the object will have the same effect as investigating the a1 method of object.
Dynamic proxy is in
B ()
{
A aa = new ();
}
This constructor transmits a parameter to generate different objects based on this parameter (the factory mode is generally used here)
The methods for generating different surveys are certainly different.

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.