【大话设计模式读书笔记——代理模式】

代理模式

代理者是指一个类别可以作为其它东西的接口。代理者可以作任何东西的接口:网络连接、内存中的大对象、文件或其它昂贵或无法复制的资源。
维基百科-代理模式

代理模式实现远程图片加载

 /// 
    /// 图片接口
    /// 
    interface IImage
    {
        void Display();
    }
 /// 
    /// 真实图片类
    /// 
   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);
        }
    }
 /// 
    /// 代理图片类
    /// 
   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

转载于:https://www.cnblogs.com/q975261413/p/8167766.html

你可能感兴趣的:(【大话设计模式读书笔记——代理模式】)