静态代理
//接口
public interface ProxyFunc {
public void request(); //对需要代理的每个方法,都需要进行静态编码,简洁但繁琐
}
//目标对象
public class Client implements ProxyFunc {
@Override
public void request() {
System.out.println("hello world");
}
}
//代理对象
public class Proxyer implements ProxyFunc {
private ProxyFunc proxyFunc;
public Proxyer(ProxyFunc proxyFunc) {
this.proxyFunc = proxyFunc;
}
@Override
public void request() {
System.out.println("在访问目标对象前,做一些控制处理");
proxyFunc.request();
System.out.println("在访问目标对象后,做一些控制处理");
}
public static void main(String[] args) {
Client client = new Client();
Proxyer proxyer = new Proxyer(client);
proxyer.request();
}
}
jdk动态代理
//接口
public interface Interface {
public void hello1();
public void hello2();
}
//被代理对象
public class Target implements Interface{
@Override
public void hello1() {
System.out.println("hello world1");
}
@Override
public void hello2() {
System.out.println("hello world2");
}
}
//代理处理器
public class Handler implements InvocationHandler {
private Interface mInterface;
public Handler(Interface mInterface) {
this.mInterface = mInterface;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("调用前处理");
Object result = method.invoke(mInterface, args);
System.out.println("调用后处理");
return result;
}
}
//测试
public class Test {
public static void main(String[] args) {
Target target = new Target();
Handler handler = new Handler(target);
Interface proxyer = (Interface) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
proxyer.hello1();
proxyer.hello2();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。