/** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ // 使用该BigImage模拟一个很大图片 public class BigImage implements Image { public BigImage() { try { // 程序暂停3s模式模拟系统开销 Thread.sleep(3000); System.out.println("图片装载成功..."); } catch (InterruptedException ex) { ex.printStackTrace(); } } // 实现Image里的show()方法 public void show() { System.out.println("绘制实际的大图片"); } }
/** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class BigImageTest { public static void main(String[] args) { long start = System.currentTimeMillis(); // 程序返回一个Image对象,该对象只是BigImage的代理对象 Image image = new ImageProxy(null); System.out.println("系统得到Image对象的时间开销:" + (System.currentTimeMillis() - start)); // 只有当实际调用image代理的show()方法时,程序才会真正创建被代理对象。 image.show(); } }
/** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public interface Image { void show(); }
/** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class ImageProxy implements Image { // 组合一个image实例,作为被代理的对象 private Image image; // 使用抽象实体来初始化代理对象 public ImageProxy(Image image) { this.image = image; } /** * 重写Image接口的show()方法 * 该方法用于控制对被代理对象的访问, * 并根据需要负责创建和删除被代理对象 */ public void show() { // 只有当真正需要调用image的show方法时才创建被代理对象 if (image == null) { image = new BigImage(); } image.show(); } }