静态代理
public interface Rent {
public void rent();
}
public class Host implements Rent{
public void rent() {
System.out.println("房东出租房子!");
}
}
public class Proxy implements Rent {
private Host host;
public Proxy(Host host) {
this.host = host;
}
public void rent() {
find();
transaction();
host.rent();
find();
}
public void find() {
System.out.println("代理找房源中...");
}
public void transaction() {
System.out.println("缴纳定金,继续交易!");
}
public void finish() {
System.out.println("完成交易!");
}
}
public class Client {
public static void main(String[] args) {
Host host = new Host();
Proxy proxy = new Proxy(host);
proxy.rent();
}
}
动态代理
public interface UserService {
public void add();
public void query();
}
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("添加数据成功!");
}
public void query() {
System.out.println("查询数据完成!");
}
}
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public void setTarget(Object o) {
target = o;
}
public Object getProxy() {
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
Object invoke = method.invoke(target, args);
return invoke;
}
public void log(String msg) {
System.out.println("log info:" + msg +" success!");
}
}
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
MyInvocationHandler mih = new MyInvocationHandler();
mih.setTarget(userService);
UserService proxy = (UserService) mih.getProxy();
proxy.add();
}
}