动态代理模式实现步骤

动态代理模式实现步骤


  • IBuyPhone 接口类
package com.mrko.proxymodel;

/**
 * 作者:Mrko on 2017/8/19 
 * 邮箱:[email protected]
 */
public interface IBuyPhone {
    void buyPhone(String name, String model);
}


  • BuyPhone 实现类
package com.mrko.proxymodel;

/**
 * 作者:Mrko on 2017/8/19 
 * 邮箱:[email protected]
 */
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 
 * 邮箱:[email protected]
 */
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 
 * 邮箱:[email protected]
 */
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
---------------------
代理之后,进行操作、
--------------------------------

  • 梳理思路:
  1. 创建实现的接口方法。IBuyPhone
  2. 实现接口方法的实现类 BuyPhone
  3. 实现InvacationHanlder接口。重写Invoke方法。
  4. 调用Proxy动态代理类。拿到了BuyPhone的实例、就可以为所欲为了。

你可能感兴趣的:(动态代理模式实现步骤)