當物件建構耗時、資源消耗大、遠端存取延遲高,或需控制存取權限時,**代理模式** 可延遲真實物件建立,直到真正需要時才具現化。代理與真實物件實作相同介面,客戶端透過代理間接存取真實物件。
public interface IImager
{
Image GetImage();
}
public class QuickImage : IImager
{
public Image GetImage()
{
return new Bitmap("Box.gif"); // 小型佔位圖
}
}
public class FinalImage : IImager
{
public Image GetImage()
{
return new Bitmap("flowertree.jpg"); // 大型真實圖片
}
}
public class ImageProxy : IImager
{
private bool _isReady = false;
private Timer _timer;
public ImageProxy()
{
// 5 秒後標記就緒 (模擬非同步載入完成)
_timer = new Timer(Callback, this, 5000, Timeout.Infinite);
}
public bool IsReady() => _isReady;
public Image GetImage()
{
IImager img = _isReady ? new FinalImage() : new QuickImage();
return img.GetImage();
}
private void Callback(object state)
{
_isReady = true;
_timer.Dispose();
}
}
public partial class Form1 : Form
{
private ImageProxy _imgProxy;
public Form1()
{
InitializeComponent();
_imgProxy = new ImageProxy();
}
protected void btLoad_Click(object sender, EventArgs e)
{
pic.Image = _imgProxy.GetImage();
}
}
| 比較項目 | 代理模式 | 適配器模式 |
|---|---|---|
| 介面 | 與真實物件**相同**介面 | 提供**不同**介面 |
| 目的 | 控制存取、延遲建立、增加行為 | 介面相容、整合不相容類別 |
| 關係 | 代理「是一個」真實物件 | 適配器「有」被適配物件 |
System.Runtime.Remoting.Proxies.RealProxy:建立透明代理ChannelFactory<T>) 本質即代理Lazy<T> 實現虛擬代理延遲初始化語意