动态代理模式实现步骤
package com.mrko.proxymodel;
/**
* 作者:Mrko on 2017/8/19
* 邮箱:mrko0630@163.com
*/
public interface IBuyPhone {
void buyPhone(String name, String model);
}
package com.mrko.proxymodel;
/**
* 作者:Mrko on 2017/8/19
* 邮箱:mrko0630@163.com
*/
public class BuyPhone implements IBuyPhone {
@Override
public void buyPhone(String name, String model) {
System.out.println("name:"+name+"-----model:"+model);
}
}
- BuyPhoneHanlder(实现 InvacationHandler接口<代理实现的第三个参数>)
package com.mrko.proxymodel;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* 作者:Mrko on 2017/8/19
* 邮箱:mrko0630@163.com
*/
public class BuyPhoneHanlder implements InvocationHandler {
private Object mObject;
public BuyPhoneHanlder(Object object) {
this.mObject = object;
}
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
System.out.println("代理之前,进行操作、");
System.out.println("---------------------");
System.out.println("method---" + method + "-----Proxy is prepare");
method.invoke(mObject, objects);
System.out.println("method---" + method + "-----Proxy is success");
System.out.println("---------------------");
System.out.println("代理之后,进行操作、");
return null;
}
}
package com.mrko.proxymodel;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/**
* 作者:Mrko on 2017/8/19
* 邮箱:mrko0630@163.com
*/
public class Cilent {
public static void main(String[] args) {
//面向接口编程
IBuyPhone buyPhone = new BuyPhone();
InvocationHandler buyPhoneHanlder = new BuyPhoneHanlder(buyPhone);
IBuyPhone buyPhoneProxy = (IBuyPhone) Proxy.newProxyInstance(buyPhoneHanlder.getClass().getClassLoader(),
buyPhone.getClass().getInterfaces(), buyPhoneHanlder);
System.out.println("--------------------------------");
buyPhoneProxy.buyPhone("mrko","Iphone8");
System.out.println("--------------------------------");
}
}
--------------------------------
代理之前,进行操作、
---------------------
method---public abstract void com.mrko.proxymodel.IBuyPhone.buyPhone(java.lang.String,java.lang.String)-----Proxy is prepare
name:mrko-----model:Iphone8
method---public abstract void com.mrko.proxymodel.IBuyPhone.buyPhone(java.lang.String,java.lang.String)-----Proxy is success
---------------------
代理之后,进行操作、
--------------------------------
- 创建实现的接口方法。IBuyPhone
- 实现接口方法的实现类 BuyPhone
- 实现InvacationHanlder接口。重写Invoke方法。
- 调用Proxy动态代理类。拿到了BuyPhone的实例、就可以为所欲为了。