静态代理模式学习

静态代理模式

代理模式(Proxy):为其他对象提供一种代理以控制对这个对象的访问。代理模式说白了就是“简单对象的 代表”,在访问对象时引入一定程度的间接性,因为这种间接性可以附加很多用途。

// 测试类
public class ProxyPattern {

    public static void main(String[] args) {
        Action userAction = new UserAction();// 被代理对象
        ActionProxy proxy = new ActionProxy(userAction);// 代理对象
        proxy.doAction();
    }
}

// 定义接口
interface Action {
    public void doAction();
}

// 用户的动作,现在我想计算一下员工一共工作了多长时间
class UserAction implements Action {

    @Override
    public void doAction() {
        System.out.println("员工开始工作。。");
    }
}

// 增加动作代理类,实现业务接口
class ActionProxy implements Action {

    private Action target;// 被代理的对象

    public ActionProxy(Action target) {
        this.target = target;
    }

    // 执行操作
    @Override
    public void doAction() {
        long start = System.currentTimeMillis();

        try {// 让线程停一会
            Thread.sleep(2000);
            target.doAction();// 执行真正的业务
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();
        System.out.println("一共工作了" + (end - start) + "毫秒");
    }

}

转载于:https://www.cnblogs.com/zxfei/p/10853196.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值