package FanShe_Factory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface ISubject2{//核心操作接口
public void eat(String foodname,int num) ;
}
class RealSubject2 implements ISubject2{
@Override
public void eat(String foodname, int num) {
System.out.println("我要吃"+num+"斤的"+foodname);
}
}
class ProxySubject2 implements InvocationHandler{
//传入真实业务类
private Object realsubject;
//将真实业务类与代理类绑定
public Object bind(Object realsubject ) {
this.realsubject=realsubject;
return Proxy.newProxyInstance(realsubject.getClass().getClassLoader(),
realsubject.getClass().getInterfaces(), this);
}
public void before() {
System.out.println("代理类处理前");
}
public void after() {
System.out.println("代理类处理后");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
this.before();
Object ret=method.invoke(this.realsubject, args);
this.after();
return ret;
}
}
public class FanShe_DongTaiDaiLi {
public static void main(String[] args) {
ISubject2 iSubject=(ISubject2) new ProxySubject2().bind(new RealSubject2());
iSubject.eat("肉", 1);
}
}