【静态代理】访问其他类的方法的方法(继承/聚合)

版权声明:仅提供学习参考使用,如若转载请说明出处谢谢! https://blog.csdn.net/weixin_44718300/article/details/90049329

用   计算   方法中   代码块的    运行时间   举例

1.创建一个坦克移动的接口

public interface Movieable {

void movie();

}

2.第一种方法直接计算

public class Tank implements Movieable{
	@Override
	public void movie() {
		//记录时间方式一
//		long start = System.currentTimeMillis();
		System.out.println("坦克移动。。。。");
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
//		long end = System.currentTimeMillis();
//		System.out.println("程序运行时间:"+(end-start));
	}

}

3、第二种方法创建一个Tank2继承Tank,重写Tank的方法

public class Tank2 extends Tank{
	 public void movie() {
		 //方式二重写父类方法
		 long start = System.currentTimeMillis();
		 super.movie();
		 long end = System.currentTimeMillis();
		 System.out.println("程序运行时间:"+(end-start));
	 }
	
}

4.第三种方法聚合      创建一个Tank3实现Tank同样的接口调用Tank的方法

public class Tank3 implements Movieable{
	//聚合(一个类里有另外一个类的对象)
	
	public Tank3(Tank t) {
		super();
		this.t = t;
	}
	Tank t;
	//方式三聚合实现:实现和Tank同样的接口,调用Tank的move方法
	
	@Override
	public void movie() {
		long start = System.currentTimeMillis();
		t.movie();
		long end = System.currentTimeMillis();
		System.out.println("程序运行时间:"+(end-start));
	}

}

5.创建测试类

public class Test {
	public static void main(String[] args) {
		Movieable m = new Tank();
		Movieable m2 = new Tank2();
		Movieable m3 = new Tank3(new Tank());
//		m.movie();
//		m2.movie();
		m3.movie();
	}

}

聚合为低耦合,加入多加入了一个记录方法开始和结束的日志的时候,我想要先记录日志,后记录时间!OK,这个功能聚合和继承都很容易做到,但是我想要先记录时间,后记录日志呢?    显而易见,继承要进行修改是很麻烦的

继承就不看了,我们看聚合的代码

1、记录日志的类

public class TankLogProxy implements Movieable{
	//聚合(一个类里有另外一个类的对象)
	
	public TankLogProxy(Movieable t) {
		super();
		this.t = t;
	}
	Movieable t;
	//方式三聚合实现:实现和Tank同样的接口,调用Tank的move方法
	
	@Override
	public void movie() {
		
		System.out.println("开始运行。。。。。");
		t.movie();
		System.out.println("运行结束。。。。。");
		
	}
}

2、记录运行时间的类

public class TankTimeProxy implements Movieable{
	//聚合(一个类里有另外一个类的对象)
	
	public TankTimeProxy(Movieable t) {
		super();
		this.t = t;
	}
	Movieable t;
	//方式三聚合实现:实现和Tank同样的接口,调用Tank的move方法
	
	@Override
	public void movie() {
		long start = System.currentTimeMillis();
		t.movie();
		long end = System.currentTimeMillis();
		System.out.println("程序运行时间:"+(end-start));
	}
 
}

3、先记录日志,后记录时间(日志在外层)

public class Test {
	public static void main(String[] args) {
		Tank t = new Tank();
		TankTimeProxy ttp = new TankTimeProxy(t);
		TankLogProxy tlp = new TankLogProxy(ttp);
		Movieable m = tlp;
		m.movie();
	}
}

如果想要把时间放在外层 ,改一下位置就好了,不用像继承那样要弄无线个类

猜你喜欢

转载自blog.csdn.net/weixin_44718300/article/details/90049329