内容都是从Tom老师的书中摘抄,记录下来方便自己学习。
代理模式是指为其他对象提供一种代理,以控制这个对象的访问。代理对象在客户端和目标对象之间起到中介的作用,代理模式属于结构型设计模式。使用代理模式的两个目的:一、保护目标对象,二是增强目标对象。
静态代理
public interface Person {
void findLove();
}
public class Son implements Person {
public void findLove() {
System.out.println("son1111");
}
}
public class Father {
private Son son;
public Father(Son son) {
this.son = son;
}
public void findLove(){
System.out.println("father111");
this.son.findLove();
System.out.println("1111");
}
}
public class Main {
public static void main(String[] args) {
Father father=new Father(new Son());
father.findLove();
}
}
动态代理
public interface Person {
void findLove();
}
public class JDKMeiPo implements InvocationHandler {
private Object target;
public Object getInstance(Object target) throws Exception{
this.target=target;
Class<?> clazz=target.getClass();
return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
Object object=method.invoke(this.target,args);
after();
return object;
}
private void before(){
System.out.println(" before :11111");
}
private void after(){
System.out.println("after :22222");
}
}
public class Customer implements Person {
@Override
public void findLove() {
System.out.println("gaofushuai");
}
}
public class Test {
public static void main(String[] args) {
try {
Person obj= (Person) new JDKMeiPo().getInstance(new Customer());
obj.findLove();
}catch (Exception e){
e.printStackTrace();
}
}
}