–原作者:尚硅谷-宋红康
静态代理&动态代理
静态代理
interface ClothFactory {
void productCloth();
}
class NikeClothFactory implements ClothFactory {
public NikeClothFactory() {
}
@Override
public void productCloth() {
System.out.println("Nike's Factory Begin Product Cloth!");
}
}
class ProxyFactory implements ClothFactory {
private ClothFactory cf;
public ProxyFactory(ClothFactory cf) {
this.cf = cf;
}
@Override
public void productCloth() {
System.out.println("方法一:开始执行");
cf.productCloth();
System.out.println("方法二:开始执行");
}
}
public class ProxyTest {
public static void main(String[] args) {
NikeClothFactory ncf = new NikeClothFactory();
ProxyFactory pf = new ProxyFactory(ncf);
pf.productCloth();
}
}
动态代理
public class DynamicProxyTest {
public static void main(String[] args) {
NikeClothFactory nck = new NikeClothFactory();
MyInvocationHandler mih = new MyInvocationHandler();
ClothFactory cf = (ClothFactory) mih.getProxy(nck);
cf.productCloth();
}
}
class MyInvocationHandler implements InvocationHandler {
// 被代理类的对象
private Object obj;
// 给被代理类对象赋值,并创建代理类的对象
public Object getProxy(Object obj) {
this.obj = obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("方法一:开始执行!");
// 执行被代理类方法
Object executeResult = method.invoke(obj, args);
System.out.println("方法二:开始执行!");
return executeResult;
}
}