静态代理模式学习

静态代理模式

代理模式(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) + "毫秒");
	}

}
posted on 2019-05-12 18:38  行之间  阅读(200)  评论(0编辑  收藏  举报