设计模式之动态代理

最近在学设计模式,这里介绍下动态代理模式及总结:

在平时开发项目中比如添加日志,在每个action 前或后会加写日志,来记录请求信息,这里如果每个action的方法后面加会很多也会很复杂这里我们一般采用的是用spirng的AOP(如果你用spring的话)实际springAOP 的设计也是用到了动态代理模式和适配器模式这里写下代码:

这先举个列子来说明下动态代理模式,我以数学计算为例,每次计算前后都会加上一些日志如下:

public interface ArithmeticCalculator {

    int add(int i,int j);

    int div(int i,int j);

}

下面添加一个计算的实现类:

@Component
public class ArithmeticCalculatorImpl implements ArithmeticCalculator{

    @Override
    public int add(int i, int j) {
        return i + j;
    }

    @Override
    public int div(int i, int j) {
        return i/j;
    }
}

下面添加一个在结果返回前打印一行日志:

@Component
public class ArithmeticCalculatorProxy {

    @Autowired
    private ArithmeticCalculator target;

    public ArithmeticCalculator getLoggingProxy(){
        ArithmeticCalculator proxy = null;
        ClassLoader loader = target.getClass().getClassLoader();
        Class[] interfaces = new Class[]{ArithmeticCalculator.class};
        InvocationHandler h = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("begin execute "+method.getName()+" method");
                Object result = method.invoke(target, args);
                System.out.println(method.getName()+" execute success result is :"+result);
                return result;
            }
        };
        proxy = (ArithmeticCalculator) Proxy.newProxyInstance(loader,interfaces,h);
        return proxy;
    }
}

再写一个测试程序:

public class Main {

    public static void main(String[] args){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:cc.MAT-INFO/applicationContext.xml");
        ArithmeticCalculator proxy =ctx.getBean(ArithmeticCalculatorProxy.class).getLoggingProxy();
        proxy.add(2,3);
        proxy.div(9, 3);

    }
}

执行结果:

四月 02, 2015 10:35:35 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5d855f: startup date [Thu Apr 02 10:35:35 CST 2015]; root of context hierarchy
四月 02, 2015 10:35:35 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [cc.MAT-INFO/applicationContext.xml]
begin execute add method
add execute success result is :5
begin execute div method
div execute success result is :3

代码比较简单,故没写注释

 

转载于:https://www.cnblogs.com/javaavaj/p/4386217.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值