概述
Lenovo类实现了SaleComputer接口,有卖电脑和展示两个方法。现在要用动态代理的设计模式将它的实例进行增强。
定义接口
public interface SaleComputer {
String sale(double money);
void show();
}
定义被代理类
public class Lenovo implements SaleComputer{
@Override
public String sale(double money) {
System.out.println("a computer costs " + money + " yuan");
return "computer" + money;
}
@Override
public void show() {
System.out.println("show.....");
}
}
实现动态代理
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
// 测试被代理类
SaleComputer lenovo = new Lenovo();
lenovo.sale(1000);
lenovo.show();
System.out.println("=================================");
SaleComputer proxy_lenovo = (SaleComputer)Proxy.newProxyInstance(lenovo.getClass().getClassLoader(), lenovo.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("test");
Object obj = method.invoke(lenovo, args);
return obj;
}
});
proxy_lenovo.show();
}
}