Static proxy :

java Agency is a model -- The proxy pattern . Adopt agent mode , Without changing the target class code , By proxy object , To add extra features ( For example, log detection is added ) Or just part of the behavior of the target object .

java in , Agents are divided into static agents and dynamic agents .

Static proxy : My understanding is that programmers create or generate proxy classes themselves or with some tools . Before use , The proxy class already exists .

A dynamic proxy : Different from static proxy , It's dynamic , No need for programmers to create their own , Just use the existing dynamic proxy class library (jdk A dynamic proxy ,cglib) Call some methods of some classes , Generate agent classes dynamically . The proxy class does not exist before it is used . When to use , When to create . Is dynamic .

Static proxy :

There are two ways to implement a static proxy .

1. synthesis

That is, the target class is a global member of the proxy class . You need the target class to implement the interface

Interface :

package com.wtd.staticproxy;
public interface Moveable {
void move();
}

Target class :

package com.wtd.staticproxy;
import java.util.Random;
/**
* @desc Car: Proxied object , Real object
* */
public class Car implements Moveable { @Override
public void move() {
try {
System.out.println("the car is running");
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

proxy class :

package com.wtd.staticproxy;
/**
* @desc Static proxy The second way : synthesis .
* Static proxy , To put it bluntly , It's manual creation proxy class . There are two ways to manually create [ Inherit , synthesis ]
* */
public class Car2 implements Moveable {// proxy class : Must implement a unified interface with the proxy class
Car car;// The proxy class ( Real class )
public Car2(Car car) {
super();
this.car= car;
}
@Override
public void move() {
System.out.println("the car start");// Amateur methods
long startTime= System.currentTimeMillis();// Amateur methods
car.move();// Call the function method of the proxied class
long endTime= System.currentTimeMillis();// Amateur methods
System.out.println("the car stop,use time:"+ (endTime-startTime)+"ms");// Amateur methods
} }

Test class :

package com.wtd.staticproxy;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Car car = new Car();// Create the proxied class ( Real class )
Moveable m2= new Car2(car);// Create a proxy class
m2.move();
} }

output:

the car start
the car is running
the car stop,use time:681ms

2. Inherit

The proxy class inherits the target class . There is no need for the target class to inherit the interface . But the target class must not be final modification

Target class :

package com.wtd.staticproxy;
import java.util.Random;
/**
* @desc Car: Proxied object , Real object
* */
public class Car { public void move() {
try {
System.out.println("the car is running");
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

proxy class :

package com.wtd.staticproxy;
/**
* @desc There are two ways of static proxy , This is the first one : How to inherit 、
* The second kind : synthesis
* */
public class Car1 extends Car{
@Override
public void move() {
System.out.println(" The car started to move ");// Amateur methods
long startTime= System.currentTimeMillis();// Amateur methods
super.move();// Call the function method of the parent class
long endTime= System.currentTimeMillis();// Amateur methods
System.out.println(" The car is over , Driving :"+ (endTime- startTime)+" millisecond ");// Amateur methods
}
}

Test class :

package com.wtd.staticproxy;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Car m= new Car1();
m.move();
} }

output:

the car start
the car is running
the car stop,use time:361ms

A dynamic proxy :

principle : Similar to composition in static proxies . The proxy object must inherit an interface

Interface :

package com.wtd.dynamicproxy3;
public interface Moveable {
void move();
void run(String args);
}

Target audience ( Proxied object ):

package com.wtd.dynamicproxy3;
public class Car implements Moveable {
@Override
public void move() {
System.out.println("Car move()");
} @Override
public void run(String args) {
System.out.println("Car run()"+ args);
} }

Call the processor object :InvocationHandler object

package com.wtd.dynamicproxy3;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method; public class LogHandler implements InvocationHandler {
private Object proxied;
public LogHandler(Object proxied) {
this.proxied= proxied;
// TODO Auto-generated constructor stub
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println(
"----------proxy: "
+ proxy.getClass()
+ ", method: "
+ method+ ", args: "
+ args+ ", proxied: "
+ proxied.getClass()); return method.invoke(proxied, args);
} }

Test class :

package com.wtd.dynamicproxy3;
import java.lang.reflect.Proxy;
public class TestDynamicProxy {
public static void main(String[] args) {
Car car= new Car();
Moveable m= (Moveable) Proxy.newProxyInstance(Moveable.class.getClassLoader(),
new Class<?>[]{Moveable.class},
new LogHandler(car));
m.move();
m.run("haha");
}
}

output:

----------proxy: class com.sun.proxy.$Proxy0, method: public abstract void com.wtd.dynamicproxy3.Moveable.move(), args: null, proxied: class com.wtd.dynamicproxy3.Car
Car move()
----------proxy: class com.sun.proxy.$Proxy0, method: public abstract void com.wtd.dynamicproxy3.Moveable.run(java.lang.String), args: [Ljava.lang.Object;@5e743399, proxied: class com.wtd.dynamicproxy3.Car
Car run()haha

cglib A dynamic proxy :

principle : Similar to inheritance in static proxies . The class of the proxy object cannot be final Modified

Import first jar package :cglib-nodep-x.x.x.jar. Can be found in mvnrepository download .

Surrogate class : Parent class :realObject:

package com.wtd.cglibproxy;
/**
* Target class ; Parent class ; Surrogate class
* Can not be final Modified
* */
public class Car {
public void move() {
System.out.println("the car running");
}
}

Method interceptor class :

package com.wtd.cglibproxy;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy; public class CglibProxy implements MethodInterceptor {
private Enhancer enhancer = new Enhancer(); /**
* Set get proxy object ( That is, subclass objects ) Methods
* Need to use Enhancer
* */
public Object getProxy(Class clazz){
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
return enhancer.create();
} /**
* @author WesTward
* @param proxied: Proxied object , Target audience , Parent object
* @param method: Of the target audience Method
* @param args: Parameters of the method of the target object
* @param proxy: Proxy object
* */
@Override
public Object intercept(Object proxied, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
System.out.println("Log---------start");
proxy.invokeSuper(proxied, args);
System.out.println("Log---------end");
return null;
} }

Test class :

package com.wtd.cglibproxy;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
CglibProxy cglibProxy= new CglibProxy();
Car car = (Car) cglibProxy.getProxy(Car.class);
car.move();
} }

output:

Log---------start
the car running
Log---------end

attach :

Dynamic agent mainly uses java The reflection mechanism of .

java More articles about the agency model

  1. Java Design patterns - Dynamic agent of agent model ( With source code analysis )

    Java Design patterns - Dynamic agent of agent model ( With source code analysis ) Dynamic agent concept and class diagram Static proxies were introduced in the previous article , One of the biggest differences between dynamic agents and static agents is : Dynamic proxy is to dynamically create proxy class and its objects at execution time . The static generation in the first part ...

  2. Java Study —— The proxy pattern

    Java Three agent models in One , What is agent mode ? Agent mode is a design mode , In a nutshell, without changing the source code , Realize the function extension of the target object . For example, there is a singer named Singer, This object has a singing method called sing ...

  3. JAVA Dynamic proxy model ( Understand the principle of code from the perspective of real life )

    The so-called dynamic agent , That is, through the proxy class :Proxy Agent for , There is no direct connection between interface and implementation class , And it can be at run time (Runtime) Achieve dynamic correlation . java Dynamic proxy mainly uses java.lang.reflect Two of the bags ...

  4. JAVA Design patterns The proxy pattern

    purpose The proxy pattern (Proxy) Provides a proxy for other objects to control access to this object . The agent model is a structural model . structure

  5. java And The proxy pattern ( Big talk design patterns )

    java The agency model, as the name suggests , It's like a university , I'd like to have a cold coke , But I'm playing games again , So I asked my roommate to bring coke back for me , In short, my roommate is an agent , And buying coke is what needs to be done . This is my understanding of the agency model Big talk design patterns - class ...

  6. JAVA The agent model in China

    The proxy pattern In some cases , A customer doesn't want or can't directly reference an object , At this time, we can call it “ agent ” Third party to achieve indirect reference . Proxy objects can play a role between client and target objects The role of mediation , And you can get rid of the client can't through the proxy object ...

  7. 【Java】 The proxy pattern 、 The reflex mechanism - A dynamic proxy

    For the proxy pattern and dynamic proxy, refer to :https://www.cnblogs.com/gonjan-blog/p/6685611.html Here is my personal understanding by referring to the examples in the blog . The proxy pattern : Methods that access a class ...

  8. Java Design patterns — The proxy pattern

    The proxy pattern (Proxy Pattern) It's also called delegation mode , It's a very high usage model . The definition is as follows :     Provides a proxy for other objects to control access to this object . Personal understanding :        The proxy pattern encapsulates the original class , ...

  9. Java Design patterns の The proxy pattern

    Catalog   The proxy pattern 1.1. Static proxy   1.2. A dynamic proxy 1.3.Cglib agent The proxy pattern agent (Proxy) It's a design pattern , Provides additional access to the target object ; That is, access the target object through the proxy object . The advantage of this is ...

Random recommendation

  1. Summary of single linked list without header ---- from a Delete from the list b There are the same characters in the linked list ID Those nodes of

    #include"head.h" struct Student* del_same_ID(struct Student*p1, struct Student*p2) { struc ...

  2. install Django, function django-admin.py startproject project name , There is no designated engineering solution after !!

        Blog for the first time ,,,,, The premise of my tutorial is that you should have installed it correctly python and Django 了 , Okay , No more bullshit , Let's get to the point ! You're not very concerned about running yourself right now django-admin.py startpr ...

  3. asp.net Export the data as excel

    This paper introduces c# How to use DataTable export Excel, As for other export methods , There is no introduction here ! 1. Read data from database , obtain DataTable: DataTable dt = HelperExecute ...

  4. android Learning notes 19—— Dialog box (DatePickerDialog、TimePickerDialog)

    DatePickerDialog.TimePickerDialog ==> DatePickerDialog.TimePickerDialog function . The usage is simple , Operation steps : 1. adopt new The key ...

  5. centos msyql Installation and configuration

    Mysql It is easy to learn . Small size and other advantages , It is very popular with beginners of programming and development Tools / raw material Access Internet Of Centos Computer install Mysql 1 Centos 6.6 Lower installation Mysql It's simple , yum list ...

  6. Write one with yourself startWith Similar judgment method

    package com.hanqi.lianxi; import java.util.Scanner; public class startWith {        // I want to be the one with you startWit ...

  7. SQLSERVER False deletion Windows The logged in user

    SQLSERVER Deleted... By mistake Windows Login user authentication mode uses Windows The solution to authentication   SQLSERVER False deletion Windows Login user authentication mode uses Windows The solution to authentication I read this article today ...

  8. ( secondary ) HDU 1542 Atlantis, Scan line .

    Problem Description There are several ancient Greek texts that contain descriptions of the fabled is ...

  9. MySQl The database will sql Statement enhanced

    This article continues from the previous one <mysql Must be sql sentence >:http://blog.csdn.net/qq_32059827/article/details/51763950 This one belongs to the enhanced version , Questions and sq ...

  10. [Swift]LeetCode923. Many possibilities of the sum of three | 3Sum With Multiplicity

    Given an integer array A, and an integer target, return the number of tuples i, j, k  such that i &l ...