设计模式—代理模式

代理模式
代理模式就是给某一个对象创建一个代理对象,有这个代理对象控制对原对象的引用,而创建这个代理对象后可以在调用原对象时增加一些额外的操作。

普通代理
接口类Sourceable.java

public interface Sourceable {  
    public void method();  
}

原对象类Sourceable.java

public class Source implements Sourceable {  

    @Override  
    public void method() {  
        System.out.println("the original method!");  
    }  
}

代理类Proxy.java

public class Proxy implements Sourceable {  

    private Source source;  
    public Proxy(){  
        super();  
        this.source = new Source();
    }  
    @Override  
    public void method() {  
        before();  
        source.method();  
        after();  
    }  
    private void after() {  
        System.out.println("after proxy!");  
    }  
    private void before() {  
        System.out.println("before proxy!");  
    }  
} 

测试类

public class ProxyTest {  

    public static void main(String[] args) {  
        Sourceable source = new Proxy();  
        source.method();  
    }  
}

动态代理
动态代理不需要对每个类,都重写代理类。

JDK的java.lang.reflect包下有个Proxy类,它是构造代理类的入口。newProxyInstance方法就是创建代理对象的方法。

newProxyInstance有三个参数:ClassLoader,用于加载代理类的Loader类,通常这个Loader和被代理的类是同一个Loader类;Interfaces,是要被代理的那些接口;InvocationHandler,用于执行出了被代理接口中方法之外的用户自定义操作,它也是用户需要代理的最终目的。

接口类Calculator.java

package dproxy;

public interface Calculator {
    int add(int a,int b);
}

接口实现类CalculatorImpl.java

package dproxy;

public class CalculatorImpl implements Calculator{

    @Override
    public int add(int a, int b) {
        int result = a+b;
        System.out.println("计算结果:"+result);
        return result;
    }

}

调用前后操作类LogHandler.java

package dproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class LogHandler implements InvocationHandler{
    Object obj;

    public LogHandler(Object obj){
        this.obj = obj;
    }

    public Object invoke(Object obj1, Method method, Object[] args)
            throws Throwable {
        this.doBefore();
        Object o = method.invoke(obj, args);
        this.doAfter();
        return o;
    }

    public void doBefore(){
        System.out.println("------调用代理类前 ,before-------");
    }
    public void doAfter(){
        System.out.println("------调用代理类前 ,after-------");
    }
}

测试类

package dproxy;

import java.lang.reflect.Proxy;

public class Test {

    public static void main(String[] args){
        Calculator calculator = new CalculatorImpl();
        LogHandler lh = new LogHandler(calculator);

        Calculator proxy = (Calculator) Proxy.newProxyInstance(calculator.getClass().getClassLoader(), calculator.getClass().getInterfaces(), lh);

        proxy.add(1, 1);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值