代理设计模式的原理:
使用一个代理对象将对象包装起来,然后用该代理对象取代原始对象,任何对原始对象的调用都要通过代理,代理决定是否以及何时将方法调用转到原始对象上。
使用静态代理的特点:
代理类和目标对象的类都是在编译期间确定下来,不利于程序的扩展。同时,每一个代理类只能为一个接口服务,这样一来程序的开发中必然产生过多的代理。于是我们想最好可以通过一个代理类来完成全部的代理功能。
静态代理代码片段:
public class TestClothProduct {
public static void main(String[] args) {
NikeClothFactory nike = new NikeClothFactory();
ProxyFactory proxy = new ProxyFactory(nike);
proxy.produceCloth();
}
}
interface ClothFactory {
void produceCloth();
}
class NikeClothFactory implements ClothFactory {
@Override
public void produceCloth() {
System.out.println("Nike工厂生产衣服!");
}
}
class ProxyFactory implements ClothFactory {
ClothFactory cf;
public ProxyFactory(ClothFactory cf) {
this.cf = cf;
}
public void produceCloth() {
System.out.println("我是代理类,收取代理费用$1000!");
cf.produceCloth();
}
}
动态代理是指客户通过代理类来调用其它对象的方法,并且是在程序运行时根据需要动态创建目标类的代理对象。
使用动态代理技术之后:
/**
* 动态代理的使用,体会反射式动态语言的关键。
*/
interface Subject {
void action();
}
// 被代理类
class RealSubject implements Subject {
public void action() {
System.out.println("我是被代理类,需要被执行!");
}
}
class MyInvocationHandler implements InvocationHandler {
Object obj;//实现了接口的被代理类的对象的声明
/**
* ①给被代理的对象实例化
* ②返回一个代理类的对象
*
* @param object
* @return
*/
public Object blind(Object object) {
this.obj = object;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnVlue = method.invoke(obj, args);
return returnVlue;
}
}
public class TestProxy {
public static void main(String[] args) {
// 1.创建被代理类的对象
RealSubject real = new RealSubject();
// 2.创建一个实现了InvocationHandler接口的类对象
MyInvocationHandler handler = new MyInvocationHandler();
// 3.调用blind(),动态返回一个同样实现了real所在类实现的接口的代理类的对象。
Object obj = handler.blind(real);
Subject sub = (Subject) obj;
sub.action();
// 再举例
NikeClothFactory nike = new NikeClothFactory();
ClothFactory cf = (ClothFactory) handler.blind(nike);
cf.produceCloth();
}
}