设计模式代理模式

/// <summary>
    
/// 天气预报接口:代理接口
    
/// </summary>
    public interface IWeather
    {
        /// <summary>
        
/// 获取天气信息
        
/// </summary>
        
/// <returns></returns>
        string GetWeatherInfo();
    }

    /// <summary>
    
/// 中央天气预报,实际业务类,实现具体的功能
    
/// 该类部署在中央气象台的服务器上,我们要直接调用该类的
    
/// 话需要经过很多步骤:1,建立连接 2,处理通讯协议 3,异常处理 等等
    
/// </summary>
    public class CnWeather : IWeather
    {
        public string GetWeatherInfo()
        {
            return string.Format("{0},天气:晴 风力3-4级",DateTime.Now.ToShortDateString());
        }
    }

    /// <summary>
    
/// 代理类,用它来封装和真实代理的交互过程,
    
/// 客户端调用这个代理类就可以了,不用关心和远程
    
/// 对象的复杂交互问题,由这个代理类来搞定就可以了。
    
/// </summary>
    public class LocalCnWeather : IWeather
    {
        private IWeather mWeather = new CnWeather();

        private void ConnectToRemoteServer()
        {
            Console.WriteLine("与远程服务建立连接以调用真实的远程对象");
        }

        private void HandleRemoteException(Exception ex)
        {
            Console.WriteLine("处理远程的异常。"+ex);
        }

        private void CloseRemoteConnection()
        {
            Console.WriteLine("远程连接关闭");
        }
        

        public string GetWeatherInfo()
        {
            ConnectToRemoteServer();
            string retMsg = string.Empty;
            try
            {
                retMsg= mWeather.GetWeatherInfo();
            }
            catch (Exception ex)
            {
                HandleRemoteException(ex);
            }
            finally
            {
                CloseRemoteConnection();
            }

            return retMsg;
        }
    }



 public static void ProxyPattern()
        {
            IWeather w = new LocalCnWeather();

            Console.WriteLine(w.GetWeatherInfo());

            //一,代理模式主要目的:
            
//1,简化对真实对象的调用,降低复杂度;
            
//隔离客户端和真实对象的耦合,用代理对象来处理与真实对象的
            
//交互过程。
            
//2,限制对真实对象的访问,比如只想让客户端调用真实
            
//对象的一部分功能。 
            
//3,总之代理模式就是隔开调用者和真实对象,让二者不直接打交道。
            
//二,代理模式实际应用:1,WebService,WCF  2,邮局
        }
原文地址:https://www.cnblogs.com/imap/p/2618781.html