动态代理模式

.

1
2
3
4
5
6
/**
* 通过reflect反射实现
*/
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

// 接口

1
2
3
4
public interface Waiter {
// 服务功能
public void service();
}

// 接口实现类:女服务员

1
2
3
4
5
6
public class Waitress implements Waiter {
@Override
public void service() {
System.out.println("女服务员正在服务...");
}
}

// 服务员经理

1
2
3
4
5
6
7
8
9
10
11
12
public class WaiterManager {
/**
* 通过经理拿到女服务员的功能代理对象Waiter proxy
*/
public static Waiter getWaitressProxy(Waitress ress){
// Proxy代理类的静态实例化方法newProxyInstance
//参数:被代理对象的类的加载器、接口、InvocationHandler接口的实现类
Waiter proxy = (Waiter) Proxy.newProxyInstance(ress.getClass().getClassLoader(), ress.getClass().getInterfaces(), new MyWaitressHandler(ress));

return proxy; // 返回女服务员的代理对象
}
}

// InvocationHandler动态代理接口的实现类

1
2
3
4
5
6
7
class MyWaitressHandler implements InvocationHandler{

private Waiter w;

MyWaitressHandler(Waiter w){ // 实参是Waitress ress
this.w = w;
}

// 重写InvocationHandler接口的invoke方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 执行服务功能:
* 在该方法里,经理不仅可以决定是否让服务员进行服务,还可以对服务功能进行完善。
* (服务前请微笑,服务后请鞠躬。)
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// 服务前请微笑
System.out.println("微笑...");

// method是waiter中service()方法的对象
// 形参w.service() --> 实参ress.service()
// 执行服务功能
method.invoke(w, args);

// 服务后请鞠躬
System.out.println("鞠躬...");

return null;
}

// 测试

1
2
3
4
5
6
7
    @Test
public void run2(){
Waitress ress = new Waitress();
Waiter proxy = WaiterManager.getWaitressProxy(ress);
proxy.service(); //微笑…女服务员正在服务…鞠躬…
}
}

---------------- The End ----------------
0%