首页 > 其他 > 详细

代理模式

时间:2019-12-22 17:17:30      阅读:89      评论:0      收藏:0      [点我收藏+]

静态代理

(略)

动态代理分为

1、基于接口的动态代理,JDK官方的Proxy类,被代理的类至少实现一个接口。

2、借助第三方CGLib类,被代理的类不是被final修饰的最终类。

 

样例

接口类

public interface IActor {

    public void basicAct(float money);

    public void dangerAct(float money);
}

实现类

public class Actor implements IActor {

    public void basicAct(float money) {
        System.out.println("Begin basic act, get " + money);
    }

    public void dangerAct(float money) {
        System.out.println("Begin danger act, get " + money);
    }
}

业务逻辑

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

public class Client {

    public static void main(String[] args) {

        final Actor actor = new Actor();

        IActor proxyActor = (IActor) Proxy.newProxyInstance(actor.getClass().getClassLoader(),
                actor.getClass().getInterfaces(), new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        String name = method.getName();
                        Float money = (Float) args[0];
                        Object rtValue = null;
                        if ("basicAct".equals(name)) {
                            if (money < 2000) {
                                rtValue = method.invoke(actor, money/2);
                            }
                        }
                        if ("dangerAct".equals(name)) {
                            if (money >= 5000) {
                                rtValue = method.invoke(actor, money/2);
                            }
                        }

                        return rtValue;
                    }
                });

        proxyActor.basicAct(8000f);
        proxyActor.dangerAct(50000f);
    }
}

代理模式

原文:https://www.cnblogs.com/jerryleeplus/p/12080133.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!