设计模式之代理模式(第二篇)

在SpringAOP学习过程中,知道了AOP底层就是通过动态代理实现的,拦截器也是。个人认为拦截器和aop是同一样东西,只是适用的地方有点不同,基本通用,如果您觉得我说的不对,也可留言告知楼主,互相成长,哈哈。言归正传,代理分为静态代理和动态代理。本文只讲动态代理。


全部文件 2个类1个节口:如下图


MapleClass
MapleClassProxy
MapleInterface
具体代码:

package com.luyo.MapleTest;

/**
 * Created by Administrator on 2016/11/15.
 */
public interface MapleInterface {
    public void method1();
    public void method2();
    public void method3();
}


package com.luyo.MapleTest;

/**
 * Created by Administrator on 2016/11/15.
 */
public class MapleClass implements MapleInterface {


    public void method1() {
        System.out.println("this  is  method1");

    }

    public void method2() {
        System.out.println("this is  method2");
    }

    public void method3() {
        System.out.println("this is  method3");
    }


    public static void main(String[] args) {

//        MapleInterface mapleClass = new MapleClass();
//        MapleDecorateAClass mapleDecorateAClass = new MapleDecorateAClass(mapleClass);
//        mapleDecorateAClass.method1();
//        mapleDecorateAClass.method2();
//        mapleDecorateAClass.methodA();
//        MapleDecorateBClass mapleDecorateBClass = new MapleDecorateBClass(mapleDecorateAClass);
//        mapleDecorateBClass.method1();
//        mapleDecorateBClass.methodB();

        MapleInterface mapleClass = new MapleClass();
        MapleInterface mapleClassProxy = (MapleInterface) new MapleClassProxy(mapleClass).getProxy();
        mapleClassProxy.method1();
        mapleClassProxy.method2();
        mapleClassProxy.method3();

    }
}
package com.luyo.MapleTest;


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

/**
 * Created by Administrator on 2016/11/15.
 */
public class MapleClassProxy {
    private Object target;


    public MapleClassProxy(Object target) {
        this.target = target;
    }


    InvocationHandler hr = new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("this method is invoke");
            Object reuslt = method.invoke(target, args);
            System.out.println(" method over.......");
            return reuslt;
        }
    };

    public Object getProxy() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), hr);

    }
输出结果:
this method is invoke
this  is  method1
 method over.......
this method is invoke
this is  method2
 method over.......
this method is invoke
this is  method3
 method over.......





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值