简介
代理模式给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用
实际应用场景
买火车票不一定在火车站买,也可以去代售点
UML
1、静态代理
2、动态代理
代码实现
/**
* @author liuyongtao
* @since 2021-3-15 12:00
*/
public interface Image {
void display();
}
/**
* @author liuyongtao
* @since 2021-3-15 12:10
*/
public class PathImage implements Image {
@Override
public void display() {
System.out.println(PathImage.class.getName());
}
}
/**
* @author liuyongtao
* @since 2021-3-15 12:01
*/
public class RealImage implements Image {
@Override
public void display() {
System.out.println(RealImage.class.getName());
}
}
1、静态代理
/**
* @author liuyongtao
* @since 2021-3-15 12:02
*/
public class ProxyImage implements Image {
private Image image;
public ProxyImage(Image image) {
this.image = image;
}
@Override
public void display() {
System.out.println(image.getClass().getName() + " 执行之前。。。");
image.display();
System.out.println(image.getClass().getName() + " 执行之后。。。");
}
}
/**
* @author liuyongtao
* @since 2021-3-15 12:06
*/
public class Main {
public static void main(String[] args) {
ProxyImage proxyImage = new ProxyImage(new RealImage());
proxyImage.display();
System.out.println("==========");
proxyImage = new ProxyImage(new PathImage());
proxyImage.display();
}
}
2、动态代理(JDK)
/**
* @author liuyongtao
* @since 2021-3-15 14:01
*/
public class DynamicProxyHandler<T> implements InvocationHandler {
private T obj;
public DynamicProxyHandler(T obj) {
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(obj.getClass().getName() + " 执行之前。。。");
Object invoke = method.invoke(obj, args);
System.out.println(obj.getClass().getName() + " 执行之后。。。");
return invoke;
}
/**
* 获取代码对象
*
* @return {@link T}
* @author liuyongtao
* @since 2021-3-15 14:16
*/
public T proxy() {
return (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), this);
}
}
/**
* @author liuyongtao
* @since 2021-3-15 14:11
*/
public class Main {
public static void main(String[] args) {
DynamicProxyHandler<Image> proxyHandler= new DynamicProxyHandler<>(new RealImage());
proxyHandler.proxy().display();
System.out.println("==========");
proxyHandler= new DynamicProxyHandler<>(new PathImage());
proxyHandler.proxy().display();
}
}