设计模式——代理模式

来源:互联网 发布:java中文是什么意思 编辑:程序博客网 时间:2024/06/07 01:55
  作用是:控制和管理访问 代理对象,自己理解,就相当于代理人职务,要访问真正的名人(对象)之前要先进过代理人这一层,代理人可以决定你有多少权限程度访问名人(访问对象方法的数量)。

代理模式:远程代理,虚拟代理,动态代理。
远程代理模式:运用RMI(远程方法调用)的方式来实现,先看定义:为另一个对象提供一个替身或占位符以控制对这个对象的访问。
直接看代码吧

客户端和系统都要有同一接口,且包名要一样。

public interface MyRemote extends Remote{    public String sayHello() throws RemoteException;}

系统端

public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote{    protected MyRemoteImpl() throws RemoteException {        super();    }    @Override    public String sayHello(){        return "Server sys,hey";    }    public static void main(String[] args) {        try {            MyRemote service = new MyRemoteImpl();            LocateRegistry.createRegistry(6600);            Naming.rebind("rmi://127.0.0.1:6600/RemoteHello", service);            System.out.println("service start");        } catch (Exception e) {            // TODO: handle exception        }    }}

这里的注意点是 ,要实现UnicastRemoteObject对象,构造方法,使用注册。

客户端

    public static void main(String[] args) {        new MyRemoteClient().go();    }    public void go(){        try {            MyRemote service = (MyRemote)Naming.lookup("rmi://127.0.0.1:6600/RemoteHello");            String s = service.sayHello();            System.out.println(s);        } catch (Exception e) {            e.printStackTrace();        }    }}

用lookup来取就行了,注意里面内容要和服务端一样。

动态代理:
类图

java API已经帮你实现了代理,你只需要调用就行了,你想要代理做什么,把代码放在InvocationHandler里就行了,Proxy的任何方法都会被传入到此类中。
代码:

要处理的方法public class NonOwnerInvocationHandler implements InvocationHandler{PersonBean person;    public NonOwnerInvocationHandler(PersonBean person){        this.person = person;    }    @Override    public Object invoke(Object proxy, Method method, Object[] args)    throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{            if(method.getName().startsWith("get")){                return method.invoke(person, args);            }else if(method.getName().equals("setHotOrNotRating")){                return method.invoke(proxy, args);            }else if(method.getName().startsWith("set")){                throw new IllegalAccessException();            }else{                return null;            }    }}public class NonOwnerInvocationHandler implements InvocationHandler{PersonBean person;    public NonOwnerInvocationHandler(PersonBean person){        this.person = person;    }    @Override    public Object invoke(Object proxy, Method method, Object[] args)    throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{            if(method.getName().startsWith("get")){                return method.invoke(person, args);            }else if(method.getName().equals("setHotOrNotRating")){                return method.invoke(proxy, args);            }else if(method.getName().startsWith("set")){                throw new IllegalAccessException();            }else{                return null;            }    }}接口public interface PersonBean {    String getName();    String getGender();    String getInterests();    int getHotOrNotRating();    void setName(String name);    void setGender(String gender);    void setInterests(String interests);    void sethotnotRating(int rating);}真正的对象public class PersonBeanImpl implements PersonBean{    String name;    String gender;    String interests;    int rating;    int ratingCount = 0;    @Override    public String getName() {        // TODO Auto-generated method stub        return name;    }    @Override    public String getGender() {        // TODO Auto-generated method stub        return gender;    }    @Override    public String getInterests() {        // TODO Auto-generated method stub        return interests;    }    @Override    public int getHotOrNotRating() {        if(ratingCount == 0) return 0;        return (rating/ratingCount);    }    @Override    public void setName(String name) {        this.name = name;    }    @Override    public void setGender(String gender) {        this.gender = gender;    }    @Override    public void setInterests(String interests) {        this.interests = interests;    }    @Override    public void sethotnotRating(int rating) {        this.rating += rating;        ratingCount++;    }}测试类public class MatchMakingTestDrive {    PersonBean person;    public static void main(String[] args) {        MatchMakingTestDrive test = new MatchMakingTestDrive();        test.drive();    }    public MatchMakingTestDrive(){        person = new PersonBeanImpl();        person.setName("Joe");        person.setGender("male");        person.setInterests("swimming");        person.sethotnotRating(22);    }    public void drive(){        PersonBean ownerProxy = getOwnerProxy(person);        System.out.println("Name is " + ownerProxy.getName());        ownerProxy.setInterests("bowling,Go");        System.out.println("Interests set from owner proxy");        try{            ownerProxy.sethotnotRating(10);        }catch (Exception e) {            System.out.println("Can't set rating from owner proxy");        }        System.out.println("Rating is " + ownerProxy.getHotOrNotRating());        PersonBean nonOwnerProxy = getNonOwnerProxy(person);        try {            nonOwnerProxy.setInterests("bowling");        } catch (Exception e) {            System.out.println("Can't set hotnotRating");        }    }    PersonBean getOwnerProxy(PersonBean person){        return (PersonBean)Proxy.newProxyInstance(person.getClass().getClassLoader(),                    person.getClass().getInterfaces(),                     new OwnerInvocationHandler(person));    }    PersonBean getNonOwnerProxy(PersonBean person){        return (PersonBean)Proxy.newProxyInstance(person.getClass().getClassLoader(),                 person.getClass().getInterfaces(),                new NonOwnerInvocationHandler(person));    }}
0 0