java 代理模式(静态、jdk动态代理)

本次小案例,目标类返回的结果是string类型,值为hello world,代理类的增强效果是将目标类的结果转换为大写。。

一、静态代理

1、目标类的接口

package statics.proxy;

/**
 * 目标类的接口
 *
 * @author LZJ
 * @create 2018-07-17 21:44
 **/
public interface DoInterface {
     String doSomeThing();
}

2、目标类

package statics.proxy;

/**
 * 目标类
 *
 * @author LZJ
 * @create 2018-07-17 21:45
 **/
public class DoInterfaceImpl implements DoInterface {
    public String doSomeThing() {
        return "hello world";
    }
}

3、代理类

package statics.proxy;

/**
 * 代理类
 *
 * @author LZJ
 * @create 2018-07-17 21:48
 **/
public class ProxyClass implements DoInterface{
    DoInterface doInterface = new DoInterfaceImpl();
    public String doSomeThing() {
        return doInterface.doSomeThing().toUpperCase();
    }
}

4、测试类

package statics.proxy;

/**
 * @author LZJ
 * @create 2018-07-17 21:55
 **/
public class Test {
    public static void main(String[] args){
        System.out.println(new DoInterfaceImpl().doSomeThing());

        DoInterface proxy = new ProxyClass();
        String s = proxy.doSomeThing();
        System.out.println(s);
    }
}

5、结果:

二、动态代理之 jdk的 Proxy方式

1、目标类的接口

package dynamic.proxy;

/**
 * 目标类的接口
 *
 * @author LZJ
 * @create 2018-07-17 21:44
 **/
public interface DoInterface {
     String doSomeThing();
}

2、目标类

package dynamic.proxy;

/**
 * 目标类
 *
 * @author LZJ
 * @create 2018-07-17 21:45
 **/
public class DoInterfaceImpl implements DoInterface {
    public String doSomeThing() {
        return "hello world";
    }
}

3、生成代理类的类

package dynamic.proxy;

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

/**
 * 生成代理的工厂
 *
 * @author LZJ
 * @create 2018-07-17 21:48
 **/
public class ProxyFactory {
    private static DoInterface target = new DoInterfaceImpl();

    public static DoInterface createProxy(){
        DoInterface proxyInstance = (DoInterface)Proxy.newProxyInstance(
                target.getClass().getClassLoader(),//目标类加载器
                target.getClass().getInterfaces(),//目标类实现的接口
                new InvocationHandler() {//匿名内部类
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        Object invoke = method.invoke(target, args);
                        if (invoke != null) {
                            invoke = ((String)invoke).toUpperCase();
                        }
                        return invoke;
                    }

                });
        return proxyInstance;
    }

}

4、测试类

package dynamic.proxy;

/**
 * @author LZJ
 * @create 2018-07-17 21:55
 **/
public class Test {
    public static void main(String[] args){

        System.out.println(new DoInterfaceImpl().doSomeThing());

        DoInterface proxy = ProxyFactory.createProxy();
        String s = proxy.doSomeThing();
        System.out.println(s);
    }
}

5、结果:

猜你喜欢

转载自blog.csdn.net/qq_36898043/article/details/81089339
今日推荐