定义:
为其他对象提供一种代理以控制对这个对象的访问;
角色:
1,抽象主题类,(接口或者抽象类),抽象真实主题和代理的共有方法(如下Subject类);
2,具体实现的主题类,继承或者实现抽象主题类的抽象方法(如下RealSubject类);
3,代理类,继承实现抽象主题类,并提供传递具体实现主题类,在实现方法里面调用具体实现的主题类(如下ProxySubject类);
Subject.java
/**
* Created by Administrator on 2016/8/31.
*/
public abstract class Subject {
public abstract void visit();
}
RealSubject.java
/**
* Created by Administrator on 2016/8/31.
*/
public class RealSubject extends Subject {
@Override
public void visit() {
System.out.print("RealSubject实现visit方法");
}
}
代理类ProxySubject.java :
/**
* Created by Administrator on 2016/8/31.
*/
public class ProxySubject extends Subject {
private RealSubject realSubject; public ProxySubject(RealSubject realSubject) {
this.realSubject = realSubject;
} @Override
public void visit() {
realSubject.visit();
}
}
测试类:
/**
* Created by Administrator on 2016/8/31.
*/
public class Test {
public static void main(String[] args) {
RealSubject RealSubject = new RealSubject();
ProxySubject ProxySubject = new ProxySubject(RealSubject);
ProxySubject.visit();
}
}
运行结果:
RealSubject实现visit方法
如上为静态代理,还有通过反射来实现的动态代理:
动态代理类:DynamicProxy.java (当出现主题是接口的时候比较适合)
public class DynamicProxy implements InvocationHandler {
private Object object; public DynamicProxy(Object object) {
this.object = object;
} @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(object, args);
return result;
}
}
定义抽象主题的接口:
/**
* Created by Administrator on 2016/8/31.
*/
public interface Subject {
public abstract void visit();
}
/**
* Created by Administrator on 2016/8/31.
*/
public class RealSubject implements Subject {
@Override
public void visit() {
System.out.println("RealSubject实现visit方法");
}
}
/**
* Created by Administrator on 2016/8/31.
*/
public class ProxySubject implements Subject {
private RealSubject realSubject; public ProxySubject(RealSubject realSubject) {
this.realSubject = realSubject;
} @Override
public void visit() {
realSubject.visit();
}
}
测试类:
import java.lang.reflect.Proxy; /**
* Created by Administrator on 2016/8/31.
*/
public class Test {
public static void main(String[] args) {
System.out.println("----------------静态代理------------------");
RealSubject realSubject = new RealSubject();
ProxySubject ProxySubject = new ProxySubject(realSubject);
ProxySubject.visit();
System.out.println("----------------动态代理------------------");
DynamicProxy dynamicProxy = new DynamicProxy(realSubject);
ClassLoader classLoader = realSubject.getClass().getClassLoader();
Subject subject = (Subject) Proxy.newProxyInstance(classLoader, new Class[]{Subject.class}, dynamicProxy);
subject.visit();
}
}
测试结果:
----------------静态代理------------------
RealSubject实现visit方法
----------------动态代理------------------
RealSubject实现visit方法
在android项目里面的使用:
比如针对不同sdk版本notifition的适配,就可以
- 首先定义notifition的公共抽象类或者接口
- 然后针对不同sdk版本实现这个notifition的实现类
- 然后代理类根据不同版本,调用不同的实现类去进行适配
在J2EE服务器项目中的使用:
Spring Aop面向切面编程,底层基于动态代理来实现向具体方法中插入功能。