结构性设计模式-代理模式(Proxy)

1.原有的代码

      /// 
    /// 业务接口
    /// 
    public interface ISubject
    {
        /// 
        /// get
        /// 
        /// 
        bool GetSomething();

        /// 
        /// do
        /// 
        void DoSomething();
    }
  /// 
    /// 一个耗时耗资源的对象方法
    /// 一个第三方封装的类和方法
    /// 
    public class RealSubject : ISubject
    {
        public RealSubject()
        {
            Thread.Sleep(2000);
            long lResult = 0;
            for (int i = 0; i < 100000000; i++)
            {
                lResult += i;
            }
            Console.WriteLine("RealSubject被构造。。。");
        }

        /// 
        /// 火车站查询火车票
        /// 
        public bool GetSomething()
        {
            Console.WriteLine("坐车去火车站看看余票信息。。。");
            Thread.Sleep(3000);
            Console.WriteLine("到火车站,看到是有票的");
            return true;
        }

        /// 
        /// 火车站买票
        /// 
        public void DoSomething()
        {
            //Console.WriteLine("This is DoSomething Before");
            //try
            //{


            Console.WriteLine("开始排队。。。");
            Thread.Sleep(2000);
            Console.WriteLine("终于买到票了。。。");
            //}
            //catch (Exception)
            //{

            //    throw;
            //}
        }
    }

2.矛盾的产生

业务需求的变更需要在原来基础上增加新的逻辑,但是原本的业务已经足够复杂不想破话原来的结构,比如缓存代理

3.解决

    /// 
    /// 第三方缓存 能在内存中差常驻数据  且能获取
    /// 
    public class CustomCache
    {
        private static Dictionary<string, object> CustomCacheDictionary = new Dictionary<string, object>
            ();
        public static void Add(string key, object value)
        {
            CustomCacheDictionary.Add(key, value);
        }
        public static T Get<T>(string key)
        {
            return (T)CustomCacheDictionary[key];
        }
        public static bool Exist(string key)
        {
            return CustomCacheDictionary.ContainsKey(key);
        }
    }
   public class ProxySubject : ISubject
    {
        private static ISubject _iSubject = new RealSubject();
        public void DoSomething()
        {
            try
            {
                Console.WriteLine("This is DoSomething Before");
                _iSubject.DoSomething();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
        public bool GetSomething()
        {
            string key = $"{nameof(ProxySubject)}_{nameof(GetSomething)}";
            bool bResult = false;
            if (CustomCache.Exist(key))
            {
                bResult = CustomCache.Get<bool>(key);
            }
            else
            {
               bResult= _iSubject.GetSomething();
                CustomCache.Add(key, bResult);
            }

            return bResult;
            //return _iSubject.GetSomething();
        }


    }

4.总结

命名约束:XXXCacheProxy

你可能感兴趣的:(设计模式,设计模式)