常用的例子
静态代理
interface ClothFactory {
void productCloth();
}
// 被代理类
class NikeClothFactory implements ClothFactory {
@Override
public void productCloth() {
System.out.println("Nike工厂生产一批衣服");
}
}
// 代理类
class ProxyFactory implements ClothFactory {
ClothFactory cf;
// 创建代理类的对象时,实际传入一个被代理类
public ProxyFactory() {
this.cf = cf;
}
@Override
public void productCloth() {
System.out.println("代理开始时,收代理费$1");
cf.productCloth();
}
}
动态代理
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Subject {
void action();
}
class RealSubject implements Subject {
@Override
public void action() {
System.out.println("我是代理类!");
}
}
class MyInvocationHandler implements InvocationHandler {
Object obj;// 实现了接口的被代理类的对象的声明
//①给被代理的对象实例化②返回一个代理类的对象
public Object blind(Object obj) {
this.obj = obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
.getClass().getInterfaces(), this);
}
//当通过代理类的对象发起对被重写地方法调用时,都会转换为如下的invoke方法的调用
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
<pre name="code" class="java"> //method方法的返回值是returnVal
Object returnVal=method.invoke(obj, args);return returnVal;}}public class TestProxy {public static void main(String[] args) {//1.被代理类的对象RealSubject real=new RealSubject();//2.创建一个实现了InvocationHandler接口类的对象MyInvocationHandler handler=new MyInvocationHandler();//3.调用了blind(),动态的返回一个同样实现了real类所在类实现的接口Subject的代理类的对象Object obj=handler.blind(real);Subject subject=(Subject) obj;subject.action();//再举一例NikeClothFactory nike=new NikeClothFactory();ClothFactory proxyCloth=(ClothFactory) handler.blind(nike);proxyCloth.productCloth();}}