wangking717 写道
代理模式的作用是:为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个客户不想或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。 或者在一系列功能模块中加入一些扩展的功能模块,那个时候就会用到面向切面编程(AOP),其中就是用的代理。当然其中要实现代理的方式很多,本文讲解静态代理模式,其中SUN自己有提供JDK动态代理,也可以找开源库cglib,javasist等。
类图:
本文讲解在一个service上添加日志功能,网上可以找到追MM代理设计模式,也可以看看
public interface IUserService {
public void addUser(String username);
public void deleteUser(String username);
}
public class UserServiceImpl implements IUserService {
public void addUser(String username) {
System.out.println("adding the "+username);
}
public void deleteUser(String username) {
System.out.println("deleting the "+username);
}
}
public class UserServiceImplProxy implements IUserService {
private IUserService userService;
public UserServiceImplProxy(IUserService userService){
this.userService = userService;
}
public void addUser(String username) {
checkSecurity();
this.userService.addUser(username);
}
public void deleteUser(String username) {
checkSecurity();
this.userService.deleteUser(username);
}
public void checkSecurity(){
System.out.println("the method is checking security...");
}
}
客户端测试:
public class Test {
public static void main(String[] args) {
UserService service = new UserServiceImplProxy(new UserServiceImpl());
service.addUser("wangking");
service.deleteUser("wangking");
}
}
很简单吧?呵呵~