Java proxy mode and dynamic proxy mode _java

Source: Internet
Author: User

1, Agent Mode

An agent is a person or an agency acting on behalf of another person or another institution. In some cases, a customer does not want to or cannot directly refer to an object, and the proxy object can act as a mediator before the client and the target object.
The proxy mode provides a proxy object to an object, and the proxy object controls the reference to the original object.

Life Example: The New Year overtime is busy, not free to buy train tickets, then you can make a call to the nearby ticketing center, ask them to help you buy a ticket home, of course, this will be additional labor costs. But it is clear that the ticket center itself does not sell tickets, only the railway station to really sell tickets, the ticket center to sell you tickets are actually through the train station to achieve. This is important!

The above example, you are "customer", ticket Center is "Agent role", the railway station is "real role", selling tickets called "Abstract role"!


Proxy mode Java code example:
Abstract role: abstract class or interface

Copy Code code as follows:

Interface Business
{
void Doaction ();
}

Real role: Truly implements the business logic interface

Agent role: Does not implement the business logic interface, but calls the real role to achieve

Copy Code code as follows:

Class Businessimplproxy implements Business
{
Private Businessimpl bi;
public void Doaction ()
{
if (bi==null)
{
bi = new Businessimpl ();
}
Dobefore ();
Bi.doaction ();
Doafter ();
}
public void Dobefore ()
{
System.out.println ("Pre-processing!") ");
}
public void Doafter ()
{
System.out.println ("Post processing!") ");
}
}
Test class
Class Test
{
public static void Main (string[] args)
{
Reference variable defined as abstract role type
Business bi = new Businessimplproxy ();
Bi.doaction ();
}
}

Copy Code code as follows:

<span></span>

So, with the help of the JVM, you can dynamically generate a proxy class ("Proxy role") at run time, and we can solve the problem of code bloat in the proxy mode above, and after using dynamic proxies, the agent role will not be generated manually, but by the JVM at run time by specifying a class loader, an array of interfaces, Invokes the handler with these 3 parameters to generate dynamically.

Dynamic Proxy mode Java code example:

Copy Code code as follows:

Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Proxy;
Import Java.lang.reflect.Method;
Abstract role: Implementation of Java dynamic Proxy currently supports only interfaces, abstract classes are not supported
Interface Businessfoo
{
void Foo ();
}
Interface Businessbar
{
String Bar (String message);
}
Real role: A real way to implement business logic
Class Businessfooimpl implements Businessfoo
{
public void Foo ()
{
System.out.println ("Businessfooimpl.foo ()");
}
}
Class Businessbarimpl implements Businessbar
{
public string Bar (String message)
{
System.out.println ("Businessbarimpl.bar ()");
return message;
}
}
Dynamic roles: Dynamically generating proxy classes
Class Businessimplproxy implements Invocationhandler
{
Private Object obj;
Businessimplproxy () {
}
Businessimplproxy (Object obj) {
This.obj = obj;
}
public object Invoke (Object Proxy,method method,object[] args) throws Throwable
{
Object result = null;
Dobefore ();
result = Method.invoke (Obj,args);
Doafter ();
return result;
}
public void Dobefore () {
System.out.println ("Do something before Business Logic");
}
public void Doafter () {
System.out.println ("Do something after Business Logic");
}
public static object factory (Object obj)
{
Class cls = Obj.getclass ();
Return Proxy.newproxyinstance (Cls.getclassloader (), Cls.getinterfaces (), New Businessimplproxy (obj));
}
}
Test class
public class Dynamicproxy
{
public static void Main (string[] args) throws Throwable
{
Businessfooimpl Bfoo = new Businessfooimpl ();
Businessfoo bf = (Businessfoo) businessimplproxy.factory (Bfoo);
Bf.foo ();
System.out.println ();

Businessbarimpl Bbar = new Businessbarimpl ();
Businessbar BB = (businessbar) businessimplproxy.factory (Bbar);
String message = Bb.bar ("Hello,world");
SYSTEM.OUT.PRINTLN (message);
}
}

Program Flow Description:
New Businessfooimpl (), creates a "real role", passes to the factory method Businessimplproxy.factory (), and initializes the call processor-the class that implements Invocationhandler. and returns a dynamically created proxy class instance, because "the proxy role" also must realize the "abstract role" to provide the business logic method, therefore may transform downward to Businessbar, and assigns the value to point to Businessbar Type the reference BB.
Newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h) method is used by the programmer to specify that the parameter dynamically returns the proxy class needed, while Invoke (Object Proxy, method methods, object[] args) is dynamically invoked by the JVM at run time. When executing "Bb.bar" ("Hello,world"); method, the JVM dynamically assigns the call processor, passes the arguments to the outer layer, and invokes Method.invoke (Obj,args) for real execution!

Businessimplproxy.factory static methods are used to dynamically generate proxy classes ("Proxy roles"), dynamically generating proxy roles at run time based on different business logic interfaces Businessfoo and Businessbar. Abstract roles, agent roles, and calling processors (classes that implement the Invocationhandler interface) can all be changed, so Java's dynamic proxies are powerful.

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.