Proxy Pattern 说白了就是用一个object 去控制另外一个object的access.
Usage in JDK:
java.lang.reflect.Proxy.
java.rmi.*(whole package)
看代码比看理论舒服多了.
-
package proxy;
-
-
interface IFolder{
-
public void performOperations();
-
}
-
-
class Folder implements IFolder{
-
-
@Override
-
public void performOperations(){
-
//access folder and perform various operations like copy or cut files
-
System.out.println("Performing operations on folder");
-
}
-
}
-
-
class User{
-
String user;
-
String pass;
-
-
public User(String user, String pass){
-
super();
-
this.user = user;
-
this.pass = pass;
-
}
-
-
public String getUser(){
-
return user;
-
}
-
-
public void setUser(String user){
-
this.user = user;
-
}
-
-
public String getPass(){
-
return pass;
-
}
-
-
public void setPass(String pass){
-
this.pass = pass;
-
}
-
}
-
-
-
class FolderProxy implements IFolder{
-
Folder folder ;
-
User user;
-
-
public FolderProxy(User user){
-
this.user = user;
-
}
-
-
@Override
-
public void performOperations(){
-
if(user.getUser() .equalsIgnoreCase("dev") &&
-
user.getPass().equalsIgnoreCase("abc-123")){
-
folder = new Folder();
-
folder.performOperations();
-
}else{
-
System.out.println("You do't not have access to this folder");
-
}
-
}
-
}
-
-
-
public class ProxyPatternDemo {
-
public static void main(String[] args){
-
User user = new User("dev","abc-123");
-
FolderProxy fp = new FolderProxy(user);
-
System.out.println("when user and pass are correct");
-
fp.performOperations();
-
System.out.println("*******************************");
-
//if we get wrong user and pass
-
User wronguser = new User("abc","wrong");
-
FolderProxy fp2 = new FolderProxy(wronguser);
-
System.out.println("when user and pass are incorrect");
-
fp2.performOperations();
-
}
-
}
阅读(446) | 评论(0) | 转发(0) |