Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1783110
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Java

2017-02-11 10:36:41

Proxy Pattern 说白了就是用一个object 去控制另外一个object的access. 

Usage in JDK:
java.lang.reflect.Proxy.
java.rmi.*(whole package)

看代码比看理论舒服多了.

点击(此处)折叠或打开

  1. package proxy;

  2. interface IFolder{
  3.     public void performOperations();
  4. }

  5. class Folder implements IFolder{

  6.     @Override
  7.     public void performOperations(){
  8.         //access folder and perform various operations like copy or cut files
  9.         System.out.println("Performing operations on folder");
  10.     }
  11. }

  12. class User{
  13.     String user;
  14.     String pass;

  15.     public User(String user, String pass){
  16.         super();
  17.         this.user = user;
  18.         this.pass = pass;
  19.     }

  20.     public String getUser(){
  21.         return user;
  22.     }

  23.     public void setUser(String user){
  24.         this.user = user;
  25.     }

  26.     public String getPass(){
  27.         return pass;
  28.     }

  29.     public void setPass(String pass){
  30.         this.pass = pass;
  31.     }
  32. }


  33. class FolderProxy implements IFolder{
  34.     Folder folder ;
  35.     User user;

  36.     public FolderProxy(User user){
  37.         this.user = user;
  38.     }

  39.     @Override
  40.     public void performOperations(){
  41.         if(user.getUser() .equalsIgnoreCase("dev") &&
  42.             user.getPass().equalsIgnoreCase("abc-123")){
  43.             folder = new Folder();
  44.             folder.performOperations();
  45.         }else{
  46.             System.out.println("You do't not have access to this folder");
  47.         }
  48.     }
  49. }


  50. public class ProxyPatternDemo {
  51.     public static void main(String[] args){
  52.         User user = new User("dev","abc-123");
  53.         FolderProxy fp = new FolderProxy(user);
  54.         System.out.println("when user and pass are correct");
  55.         fp.performOperations();
  56.         System.out.println("*******************************");
  57.         //if we get wrong user and pass
  58.         User wronguser = new User("abc","wrong");
  59.         FolderProxy fp2 = new FolderProxy(wronguser);
  60.         System.out.println("when user and pass are incorrect");
  61.         fp2.performOperations();
  62.     }
  63. }

阅读(446) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~