Proxy 代理模式笔记

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();
    }

}

 

 

你可能感兴趣的:(jdk,.net)