结构

代理模式

说明

Provide a surrogate or placeholder for another object to control access to it.

为其他对象提供一个代理以控制对这个对象的访问。

适用条件

  1. 远程代理: 为一个对象在不同的地址空间提供局部代表;
  2. 虚代理: 根据需要创建开销很大的对象;
  3. 保护代理: 控制对原始对象的访问;
  4. 智能指引: 取代了简单的指针, 并在访问对象时执行一些附加操作。

实现

public interface IImage {

   void DisplayImage();

}

public class RealImage : IImage {

   private readonly string _fileName;

   public RealImage(string fileName) {
      this._fileName = fileName;
      this.LoadImageFromFile();
   }

   private void LoadImageFromFile() {
      Console.WriteLine("Load image from file {0}",     this._fileName);
   }

   public void DisplayImage() {
      Console.WriteLine("Displaying image {0}", this._fileName);
   }

}

public class ProxyImage : IImage {

   private RealImage _realImage;
   private readonly string _fileName;

   public ProxyImage(string fileName) {
      this._fileName = fileName;
   }

   public void DisplayImage() {
      if (this._realImage == null) {
         this._realImage = new RealImage(this._fileName);
      }
      this._realImage.DisplayImage();
   }
}

class Program {

   static void Main(string[] args) {
      IImage image1 = new ProxyImage("HiRes_10MB_Photo1");
      IImage image2 = new ProxyImage("HiRes_10MB_Photo2");

      image1.DisplayImage();
      image1.DisplayImage();
      image2.DisplayImage();
      image2.DisplayImage();

      Console.ReadKey();
   }

}