定义接口
public interface Buy {
void buy();
委托人
public class Student implements Buy{
@Override
public void buy() {
Log.e("TAG","买一份蛋炒饭");
}
静态代理:
public class Rider implements Buy{
private Buy buy;
public Rider(Buy buy) {
this.buy = buy;
}
@Override
public void buy() {
buy.buy();
}
调用:
Rider rider = new Rider(new Student());
rider.buy();
动态代理:
public class RiderProxy implements InvocationHandler {
private Buy buy;
public RiderProxy(Buy buy) {
this.buy = buy;
}
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
//买之前
Log.e("TAG","在宿舍中,吹着空调");
Object invoke = method.invoke(buy, objects);
//买之后
Log.e("TAG","吹着空调,吃着饭");
return invoke;
}
}
调用:
Student student = new Student();
RiderProxy proxy = new RiderProxy(student);
ClassLoader classLoader = student.getClass().getClassLoader();
Buy o = (Buy) Proxy.newProxyInstance(classLoader, new Class[]{Buy.class}, proxy);
o.buy();