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

    xiaoxiao2021-12-12  37

    在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.......
    转载请注明原文地址: https://ju.6miu.com/read-900071.html

    最新回复(0)