JAVA设计模式之代理模式:Proxy

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");  
          
    }  
} 

 

很简单吧?呵呵~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值