代理模式顾名思义是是一个类代理另外一个类来实现某些功能,也可以在功能的前后插入一些逻辑。
public interface Subject {
public void doSomething();
}
public class SubjectImp implements Subject{
public void doSomething() {
System. out .println("Subject doSomething" );
}
}
静态代理:
public class Proxy {
SubjectImp subject ;
public Proxy(SubjectImp subject) {
this .subject = subject;
}
public void preDothing() {
System. out .println("Proxy preDothing" );
}
public void dothing() {
preDothing();
subject.doSomething();
afterDothing();
}
public void afterDothing() {
System. out .println("Proxy afterDothing" );
}
}
public class ProxyClient {
public static void main(String[] args) {
SubjectImp subject = new SubjectImp();
Proxy proxy = new Proxy(subject);
proxy.dothing();
}
}
动态代理:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicProxy implements InvocationHandler {
private Object subject ;
public DynamicProxy(Object subject) {
this .subject = subject;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
beforeSubject();
Object result = method.invoke( subject, args);
afterSubject();
return result;
}
public void beforeSubject() {
System. out .println(" before subject" );
}
public void afterSubject() {
System. out .println(" after subject" );
}
}
import java.lang.reflect.Proxy;
public class DynamicProxyClient {
public static void main(String[] args) {
SubjectImp subject = new SubjectImp();
DynamicProxy handler = new DynamicProxy(subject);
Subject obj = (Subject) Proxy.newProxyInstance(handler .getClass().getClassLoader(), subject.getClass().getInterfaces(), handler);
obj.doSomething();
}
}