设计模式之静态代理。
好的不说直接上代码。
Moveable.java- package com.snow;
- public interface Moveable {
- void move();
- }
复制代码 Tank.java- package com.snow;
- import java.util.Random;
- public class Tank implements Moveable{
- @Override
- public void move() {
- //long start = System.currentTimeMillis();
- System.out.println("Tank Moving .......");
- try {
- Thread.sleep(new Random().nextInt(10000));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- //long end = System.currentTimeMillis();
- //System.out.println("time:" + (end - start));
- }
- }
复制代码 Tank2.java- package com.snow;
- public class Tank2 extends Tank{
- @Override
- public void move() {
- long start = System.currentTimeMillis();
- super.move();
- long end = System.currentTimeMillis();
- System.out.println("time:" + (end - start));
- }
- }
复制代码 Tank3.java- package com.snow;
- public class Tank3 implements Moveable{
- Tank t;
- public Tank3(Tank t) {
- super();
- this.t = t;
- }
- @Override
- public void move() {
- long start = System.currentTimeMillis();
- t.move();
- long end = System.currentTimeMillis();
- System.out.println("time:" + (end - start));
- }
- }
复制代码 简单给予说明。实现静态代理的方法有两种:
- 继承实现
- 实现同一接口聚合被代理对象
- 两者聚合比较好。因为更为灵活。
|