代理简单来说,你把你自己能要做的事,让别人代你完成,比如你把作业交给课代表,课代表转交给老师
静态代理
interface Interface{
void doSomething();
void somethingElse(String arg);
}
class RealObject implements Interface{
public void doSomething(){
System.out.println("doSomething");
}
public void somethingElse(String arg){
System.out.println("SomethingElse " + arg);
}
}
class SimpleProxy implements Interface{
private Interface proxied;
public SimpleProxy(Interface proxied){
this.proxied = proxied;
}
public void doSomething(){
System.out.println("SimpleProxy doSomething");
proxied.doSomething();
}
public void somethingElse(String arg){
System.out.println("SimpleProxy somethingElse " + arg);
proxied.somethingElse(arg);
}
}
class SimpleProxyDemo{
public static void consumer(Interface iface){
iface.doSomething();
iface.somethingElse("hello");
}
}
public class Main{
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
SimpleProxyDemo.consumer(new RealObject());
SimpleProxyDemo.consumer(new SimpleProxy(new RealObject()));
}
}
运行结果:
doSomething
SomethingElse hello
SimpleProxy doSomething
doSomething
SimpleProxy somethingElse hello
SomethingElse hello
动态代理
interface Interface{
void doSomething();
void somethingElse(String arg);
}
class RealObject implements Interface{
public void doSomething(){
System.out.println("doSomething");
}
public void somethingElse(String arg){
System.out.println("SomethingElse " + arg);
}
}
class SimpleDynamicProxyDemo{
public static void consumer(Interface iface){
iface.doSomething();
iface.somethingElse("hello");
}
}
class DynamicProxyHandler implements InvocationHandler{
private Object proxied;
public DynamicProxyHandler(Object proxied){
this.proxied = proxied;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(proxied, args);
}
}
public class Main{
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
RealObject real = new RealObject();
SimpleDynamicProxyDemo.consumer(real);
//代理对象
Interface proxy = (Interface) Proxy.newProxyInstance(
Interface.class.getClassLoader(), //类加载器
new Class[]{ Interface.class}, //继承的接口
new DynamicProxyHandler(real) //需要代理的对象
);
SimpleDynamicProxyDemo.consumer(proxy);
}
}
运行结果:
doSomething
SomethingElse hello
doSomething
SomethingElse hello
与静态代理相比,动态代理需要手动去实现代理类,需要创建一个继承InvocationHandler接口的类,去帮我们实现;然后利用Proxy.newProxyInstance去生成代理对象