首页 > 代码库 > 代理模式

代理模式

因为今天又重新学习了一下代理模式,也看了一下spring的AOP,所以今天就简单举两个例子吧,改天再来细说下

1.静态代理


interface Source{
public void method();
}


class Sourceable implements Source {

@Override
public void method() {
System.out.println("这是原始方法");

}
}


class SourceImp implements Source {
private Sourceable sourceable;

public SourceImp() {
super();
this.sourceable = new Sourceable();
}

public void before(){
System.out.println("---------before---------");
}

public void after(){
System.out.println("----------after----------");
}

@Override
public void method() {
before();
sourceable.method();
after();

}


}


public class ProxyTest {

public static void main(String[] args) {

Source sourceImp = new SourceImp();
sourceImp.method();
}
}

打印结果

技术分享

2.动态代理

interface Source{
public void method();
}

class DyProxy implements InvocationHandler{
Source source;

public DyProxy(Source source) {
this.source = source;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object res =null;
try{
System.out.println("before");
res = method.invoke(source);
System.out.println("after");
}catch(Exception e){
e.printStackTrace();
}

return res;
}

}


public class DyProxyTest{
public static void main(String[] args) {
Source source = new Sourceable();
ClassLoader classloader = source.getClass().getClassLoader();
Class[] interfaces = new Class[]{Source.class};
Source s2 = (Source)Proxy.newProxyInstance(classloader, interfaces, new DyProxy(source));
s2.method();
}
}

打印结果:

技术分享

 

代理模式