静态代理

package com.test.myproxy.jingtai;

public interface Moveable {
	public void move();
}
 
package com.test.myproxy.jingtai;

import java.util.Random;

public class Tank implements Moveable {

	@Override
	public void move() {
		System.out.println("moving...");
		try {
			Thread.sleep(new Random().nextInt(10000));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}

 

package com.test.myproxy.jingtai;

public class ProxyLogTank implements Moveable {

	public ProxyLogTank(Moveable t) {
		this.t = t;
	}

	private Moveable t;
	
	@Override
	public void move() {
		System.out.println("日志:begin");
		t.move();
		System.out.println("日志:begin");
	}
	
}
 
package com.test.myproxy.jingtai;

public class ProxyTimeTank implements Moveable {

	public ProxyTimeTank(Moveable t) {
		this.t = t;
	}

	private Moveable t;
	
	@Override
	public void move() {
		long sd = System.currentTimeMillis();
		t.move();
		long ed = System.currentTimeMillis();
		System.out.println("运行了:" + (ed - sd));
	}
	
}
 
package com.test.myproxy.jingtai;

public class Client {
	public static void main(String[] args) {
		//继承
		//Moveable m = new Tank2_2();
		//m.move();
		
		//聚合
		Moveable t = new Tank();
		
		//先时间,再日志
//		Moveable m_log = new ProxyLogTank(t);
//		Moveable m_time = new ProxyTimeTank(t);
//		m_time.move();

		
		//先日志,再时间(在时间外包层日志)
		Moveable m_time = new ProxyTimeTank(t);
		Moveable m_log = new ProxyLogTank(m_time);
		m_log.move();
	}
}

 

问题:有一辆坦克,先是给它移动的动作,然后觉得要给它记录移动时间,然后又想给它记录移动日志。

如果用继承来实现,就很麻烦,要加一个功能,就得为坦克类修改一次代码。

这里用静态代理,这样就可以随便添加组合别的功能了。

 

当然,更好的方法是用动态代理,但我目前只会代理一层,如果像上面一样,代理多层,就不会了。。。

你可能感兴趣的:(静态代理)