模擬簡單的動態代理

空霧峰發表於2020-12-15

UsbShell.java

package dontaidiali.service;

/**
 * 目標介面
 */
public interface UsbShell {
    float sell(int amount);
}

UsbKingFactory.java

package dontaidiali.factory;

import dontaidiali.service.UsbShell;

/**
 * 目標類
 */
public class UsbKingFactory implements UsbShell {
    @Override
    public float sell(int amount) {
        return 85.0f;
    }
}

MyHander.java

package dontaidiali.shangjia;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyHandler implements InvocationHandler {
    private Object target = null;

    public MyHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object res = null;
        res = method.invoke(target,args);
        if (res!=null){
            Float price = (float) res;
            price = price +15;
            res = price;
        }
        System.out.println("通過代理");
        return res;
    }
}

Test.java

package dontaidiali;

import dontaidiali.factory.UsbKingFactory;
import dontaidiali.service.UsbShell;
import dontaidiali.shangjia.MyHandler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class Test {
    public static void main(String[] args) {
        //1.建立目標物件
        UsbShell taobao = new UsbKingFactory();
        //2.建立MyHandler物件
        InvocationHandler daiLi = new MyHandler(taobao);
        //3.建立代理物件
        UsbShell proxy = (UsbShell) Proxy.newProxyInstance(taobao.getClass().getClassLoader(),
                taobao.getClass().getInterfaces(),
                daiLi);
        //4.代理物件呼叫方法
        float s = proxy.sell(1);
        System.out.println(s);
    }
}

執行結果

結果

相關文章