代理也是一个基础的设计模式,被经常用于编程中。但是,它的一个缺点是专一性或者代理和它的底层对象紧密耦合。
public class MyDynamicProxyClass implements InvocationHandler { Object obj; public MyDynamicProxyClass(Object obj) { this.obj = obj; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { String methodName = method.getName(); if(methodName.startsWith("get")){ String name = methodName.substring(methodName.indexOf("get") + 3); return method.invoke(obj, args); } else if(methodName.startsWith("set")){ String name = methodName.substring(methodName.indexOf("set") + 3); method.invoke(obj, args); return null; } else if(methodName.startsWith("is")){ String name = methodName.substring(methodName.indexOf("is") + 2); return null; } return null; } catch (Exception e) { throw e; } } }
IPerson person = new Person(); IPerson proxy = (IPerson) Proxy.newProxyInstance(person.getClass().getClassLoader(), new Class[] {IPerson.class}, new MyDynamicProxyClass(person));
public class ViewProxy implements InvocationHandler{ private Map map = new HashMap(); private Object obj; public ViewProxy(Object obj) { this.obj = obj; } public static Object newInstance(Object obj, Class[] interfaces){ return Proxy.newProxyInstance(obj.getClass().getClassLoader(), interfaces, new ViewProxy(obj)); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub String methodName = method.getName(); if(methodName.startsWith("get")){ String name = methodName.substring(methodName.indexOf("get") + 3); // return map.get(name); return method.invoke(obj, args); } else if(methodName.startsWith("set")){ String name = methodName.substring(methodName.indexOf("set") + 3); // map.put(name, args[0]); method.invoke(obj, args); return null; } else if(methodName.startsWith("is")){ String name = methodName.substring(methodName.indexOf("is") + 2); return map.get(name); } return null; } }
public interface IPerson { public String getName(); public String getAddress(); public void setName(String name); public void setAddress(String address); }
public class Person implements IPerson { private String name; private String address; @Override public String getName() { // TODO Auto-generated method stub return name; } @Override public String getAddress() { // TODO Auto-generated method stub return address; } @Override public void setName(String name) { // TODO Auto-generated method stub this.name = name; } @Override public void setAddress(String address) { // TODO Auto-generated method stub this.address = address; } }
public static void main(String[] args) { IPerson person = new Person(); IPerson proxy = (IPerson) ViewProxy.newInstance(person, new Class[] {IPerson.class}); proxy.setName("Bob Jones"); proxy.setAddress("Chicago");; System.out.println(proxy.getName() + ", " + proxy.getAddress()); }