一、代理模式
代理设计就是为其他对象提供一种代理以控制对这个对象的访问
二、静态代理
工厂接口
interface ClothFactory {
public void produceCloth();
}
被代理类
class NikeClothProduct implements ClothFactory{
@Override
public void produceCloth() {
System.out.println("生产Nike服装");
}
}
代理类
class ProxyClothFactory implements ClothFactory{
private ClothFactory clothProduct;
public ProxyClothFactory(ClothFactory clothProduct) {
this.clothProduct = clothProduct;
}
@Override
public void produceCloth() {
System.out.println("生产前工作");
clothProduct.produceCloth();
System.out.println("生产后工作");
}
}
主函数驱动测试
public class ClothProxyTest {
public static void main(String[] args) {
NikeClothProduct nikeClothProduct = new NikeClothProduct();
ProxyClothFactory proxyClothFactory = new ProxyClothFactory(nikeClothProduct);
proxyClothFactory.produceCloth();
}
}
运行结果
三、动态代理
实现Invocation类,加入通用方法
class MyInvocationHandler implements InvocationHandler{
//用于保存被代理类对象
private Object obj;
public void band(Object obj){
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//===============前置通用方法===========
System.out.println("=============前置方法=============");
//=====================================
//===============原始方法==============
Object returnVal = method.invoke(obj,args);
//=====================================
//===============后置通用方法===========
System.out.println("=============后置方法=============");
//=====================================
return returnVal;
}
}
通过Proxy类创建动态代理对象
先绑定被代理类
返回Proxy.newProxyInstance(被代理类的类加载器,被代理类的接口,InvocationHandler对象)
将其写入ProxyFactory代理类中
class ProxyFactor{
public static Object getProxyInstance(Object obj){
MyInvocationHandler handler = new MyInvocationHandler();
handler.band(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), handler);
}
}
使用
public class DynamicProxyTest {
public static void main(String[] args) {
SuperMan superMan = new SuperMan();
//载入任何对象
Human proxy = (Human) ProxyFactor.getProxyInstance(superMan);
//调用任何对象的方法都会先使用代理类方法
System.out.println(proxy.getBelief());
proxy.eat("麻辣烫");
}
}
总结
difficult