閱讀540 返回首頁    go 阿裏雲 go 技術社區[雲棲]


【設計模式】【代理模式,大圖片加載】

/**
 * Description:
 * <br/>網站: <a href="https://www.crazyit.org">瘋狂Java聯盟</a> 
 * <br/>Copyright (C), 2001-2012, 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="https://www.crazyit.org">瘋狂Java聯盟</a> 
 * <br/>Copyright (C), 2001-2012, 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="https://www.crazyit.org">瘋狂Java聯盟</a> 
 * <br/>Copyright (C), 2001-2012, 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();
	}
}


/**
 * Description:
 * <br/>網站: <a href="https://www.crazyit.org">瘋狂Java聯盟</a> 
 * <br/>Copyright (C), 2001-2012, 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();	
	}
}




最後更新:2017-04-04 07:03:38

  上一篇:go 杭電1004
  下一篇:go jsp-servlet圖像驗證碼