Linux實體連結與符號連結
阿新 • • 發佈:2020-12-15
動態代理是通過Java的反射機制,建立代理類的物件。
動態代理可以在不改變原來的程式碼的基礎上,在代理中寫增強功能的程式碼。
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);
}
}
執行結果