
一个通用的实现接口
public interface UserInterface () {//m卖房
void say(String name);
}
目标类(被代理类)
public class User implements UserInterface {//可以看成房东
@Overide
public void say(String name)() {
sout(name + "hello")
}
}
代理类
public class UserProxy() implements UserInterface {//中介
private UserInterface proxy;
public UserProxy (UserInterface proxy) {
this.proxy = proxy;
}
@Overide
public void say(String name) {
proxy.say(name);
}
}
以上就是静态代理我觉得就是代理模式
静态代理功能较为单一,我们想要的是根据运行环境动态的决定代理类的行为
目前常见的方式有基于jdk的动态代理反射实现,目标对象必须要有接口,生成的代理类是一个接口的一个实现类
再一个就是基于cglib实现,基于字节码实现,效率较低,但是目标对象不需要有接口,生成的代理类是目标类的子类,因此目标类不能是final
通用接口
package test.proxy;
public interface WhatInterface {//通用接口
void say(String what);
}
被代理类
package test.proxy;
public class What implements WhatInterface{//被代理类(目标类)
@Override
public void say(String what) {
System.out.println(what);
}
}
代理类
package test.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class WhatProxy implements InvocationHandler {//代理类
private Object obj;
public WhatProxy(Object obj) {
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("befor message");
method.invoke(obj, args);
System.out.println("after message");
return null;
}
}
执行代理方法
package test.proxy;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
WhatProxy whatProxy = new WhatProxy(new What());
WhatInterface whatInterface = (WhatInterface) Proxy.newProxyInstance(new What().getClass().getClassLoader(), new What().getClass().getInterfaces(), whatProxy);
whatInterface.say("what");
}
}