spring-Proxy
- 代理方式一
public class client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
Proxy proxy = new Proxy();
proxy.setUserServiceImpl(userService);
proxy.add();
}
}
public class Proxy implements UserService{
private UserServiceImpl userServiceimpl;
public void setUserServiceImpl(UserServiceImpl userServiceimpl) {
this.userServiceimpl = userServiceimpl;
}
@Override
public void add() {
log("add");
userServiceimpl.add();
}
public void log(String msg){
System.out.println("use " + msg + " method");
}
}
public interface UserService {
public void add();
}
`
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加一个用户");
}
- 代理方式二
public class Client {
public static void main(String[] args) {
Host host = new Host();
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setRent(host);
Rent proxy = (Rent) pih.getProxy();
proxy.rent();
}
}
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东出租房子");
}
}
public class ProxyInvocationHandler implements InvocationHandler {
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
seeHouse();
Object invoke = method.invoke(rent, args);
sign();
return invoke;
}
public void seeHouse(){
System.out.println("中介带人看房子");
}
public void sign(){
System.out.println("签合同");
}
}
public interface Rent {
public void rent();
}
- 代理方式三
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
InvocationHandler pih = new InvocationHandler();
pih.setTarget(userService);
UserService proxy = (UserService) pih.getProxy();
proxy.add();
}
}
public class InvocationHandler implements java.lang.reflect.InvocationHandler {
private Object target;
public void setTarget(Object target) {
this.target = target;
}
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
@Override
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("run "+msg+" method");
}
}