1. 意圖:
為其他對象提供一種代理以控制對這個對象的訪問
2. 別名:
surrogate替身
3. 動機
按需創建, 替代對象
4. 適用性
* 遠程代理
* 虛代理
* 保護代理
* 智能指引
5. 結構
6. 實例
- package net.yeah.fanyamin.pattern.proxy;
- /**
- * @author walter
- */
- interface Greet {
- void sayHello(String name);
- void goodBye();
- }
- class GreetImpl implements Greet {
- public void sayHello(String name) {
- System.out.println("Hello " + name);
- }
- public void goodBye() {
- System.out.println("Good bye.");
- }
- }
- public class SimpleProxy implements Greet {
- private Greet greet = null;
- SimpleProxy(Greet greet) {
- this.greet = greet;
- }
- public void sayHello(String name) {
- System.out.println("--before method sayHello");
- greet.sayHello(name);
- System.out.println("--after method sayHello");
- }
- public void goodBye() {
- System.out.println("--before method goodBye");
- greet.goodBye();
- System.out.println("--after method goodBye");
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- Greet greet = new SimpleProxy(new GreetImpl());
- greet.sayHello("walter");
- greet.goodBye();
- }
- }
利用JDK中的動態代理
- /**
- *
- */
- package net.yeah.fanyamin.pattern.proxy;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- /**
- * @author walter
- */
- public class DebugProxy implements java.lang.reflect.InvocationHandler {
- private Object obj;
- public static Object newInstance(Object obj) {
- return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
- obj.getClass().getInterfaces(), new DebugProxy(obj));
- }
- private DebugProxy(Object obj) {
- this.obj = obj;
- }
- public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
- Object result;
- try {
- System.out.println("--before method " + m.getName());
- result = m.invoke(obj, args);
- } catch (InvocationTargetException e) {
- throw e.getTargetException();
- } catch (Exception e) {
- throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
- } finally {
- System.out.println("--after method " + m.getName());
- }
- return result;
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- Greet greet = (Greet) DebugProxy.newInstance(new GreetImpl());
- greet.sayHello("walter");
- greet.goodBye();
- }
- }
動態代理確實很有價值,而且java的反射機制其實性能并不慢,只不過被代理的Object需要有個Interface就是了。
實際中,代理多用在訪問,權限控制
其實從類的實現表現形式來說,和裝飾模式,適配器模式,都比較相似,只不過具體實現意義不一樣