代理模式
代理者是指一个类别可以作为其它东西的接口。代理者可以作任何东西的接口:网络连接、内存中的大对象、文件或其它昂贵或无法复制的资源。
维基百科-代理模式
代理模式实现远程图片加载
/// <summary>
/// 图片接口
/// </summary>
interface IImage
{
void Display();
}
/// <summary>
/// 真实图片类
/// </summary>
public class RealImage : IImage
{
public RealImage(string fileName)
{
FileName = fileName;
LoadFromFile();
}
private void LoadFromFile()
{
Console.WriteLine("Loading " + FileName);
}
public String FileName { get; private set; }
public void Display()
{
Console.WriteLine("Displaying " + FileName);
}
}
/// <summary>
/// 代理图片类
/// </summary>
public class ProxyImage : IImage
{
public ProxyImage(string fileName)
{
FileName = fileName;
}
public String FileName { get; private set; }
private IImage image;
public void Display()
{
if (image == null)
image = new RealImage(FileName);
image.Display();
}
}
IImage image = new ProxyImage("HiRes_Image");
for (int i = 0; i < 10; i++)
{
image.Display();
}
输出:
Loading HiRes_Image
Displaying HiRes_Image
Displaying HiRes_Image
Displaying HiRes_Image
Displaying HiRes_Image
Displaying HiRes_Image
Displaying HiRes_Image
Displaying HiRes_Image
Displaying HiRes_Image
Displaying HiRes_Image
Displaying HiRes_Image